[英]Sinon how to stub method for unit testing a Async function
I am trying to write a unit test for an async function using mocha and sinon.js我正在尝试使用 mocha 和 sinon.js 为异步函数编写单元测试
Below is my test case下面是我的测试用例
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)
})
})
Below is the definition of the async function I am testing.下面是我正在测试的异步函数的定义。
async function getOperations (customObj, store) {
const obj = foo(topLevelcustomObj, store)
return obj
}
function foo (topLevelcustomObj, store) {
return store.peekRecord('obj', 12345)
}
The test case fails as the promise being return is rejected with a message测试用例失败,因为返回的承诺被一条消息拒绝
TypeError: store.query is not a function at Object._callee$.
类型错误:store.query 不是 Object._callee$ 的函数。
The code I am testing is not calling store.query
anywhere and also I have stubbed store.peekRecord
also so not sure how it is getting called.我正在测试的代码没有在任何地方调用
store.query
并且我也存根了store.peekRecord
所以不确定它是如何被调用的。
Your getOperations
function use async
syntax so that you need to use async/await
in your test case.您的
getOperations
函数使用async
语法,因此您需要在测试用例中使用async/await
。 And, it works fine.而且,它工作正常。
Eg index.ts
例如
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
: 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);
});
});
});
Unit test result with 100% coverage: 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 | |
---------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59639661源代码: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59639661
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.