Sinon如何为单元测试异步函数存根方法

3
我正在尝试使用mocha和sinon.js编写异步函数的单元测试。
以下是我的测试用例。
  describe('getOperations', function () {
    let customObj, store, someObj
    beforeEach(function () {
      someObj = {
        id: '-2462813529277062688'
      }
      store = {
        peekRecord: sandbox.stub().returns(someObj)
      }
    })
    it('should be contain obj and its ID', function () {
      const obj = getOperations(customObj, store)
      expect(obj).to.eql(someObj)
    })
  })

以下是我正在测试的异步函数的定义。
async function getOperations (customObj, store) {
  const obj = foo(topLevelcustomObj, store)
  return obj
}

function foo (topLevelcustomObj, store) {
    return store.peekRecord('obj', 12345)
}

测试用例失败了,因为返回的 Promise 被拒绝并带有一条消息

TypeError: store.query 不是一个函数,位于 Object._callee$。

我正在测试的代码没有调用 store.query 任何地方,而且我也已经存根化了 store.peekRecord,所以不确定它是怎么被调用的。

1个回答

3
你的getOperations函数使用了async语法,因此在测试用例中需要使用async/await。它可以正常工作。
例如:index.ts
export async function getOperations(customObj, store) {
  const obj = foo(customObj, store);
  return obj;
}

export function foo(customObj, store) {
  return store.peekRecord("obj", 12345);
}

index.test.ts:

import { getOperations } from "./";
import sinon from "sinon";
import { expect } from "chai";

describe("59639661", () => {
  describe("#getOperations", () => {
    let customObj, store, someObj;
    beforeEach(function() {
      someObj = {
        id: "-2462813529277062688",
      };
      store = {
        peekRecord: sinon.stub().returns(someObj),
      };
    });
    it("should pass", async () => {
      const obj = await getOperations(customObj, store);
      expect(obj).to.deep.eq(someObj);
    });
  });
});

100%覆盖率的单元测试结果:

  59639661
    #getOperations
      ✓ should pass


  1 passing (14ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |      100 |      100 |                   |
 index.test.ts |      100 |      100 |      100 |      100 |                   |
 index.ts      |      100 |      100 |      100 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源代码: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59639661


如果我需要在 sinon.stub().returns(someObj) 中添加一些功能,例如一些 if 语句,而不是直接返回对象,您能告诉我如何实现吗? - ashish2199
sinon.callsFake() - Ahmad Shah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接