ember.js 如何使用存根方法对异步函数进行单元测试

ki1q1bka  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(145)

我正在尝试使用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)
}

测试用例失败,因为返回的承诺被拒绝,并显示消息
TypeError:store.query不是Object._callee$上的函数。
我正在测试的代码在任何地方都没有调用store.query,而且我还存根了store.peekRecord,所以不确定它是如何被调用的。

nhaq1z21

nhaq1z211#

你的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

相关问题