Javascript Sinon如何使用存根方法对异步函数进行单元测试
我正在尝试使用mocha和sinon.js为异步函数编写单元测试 下面是我的测试用例Javascript Sinon如何使用存根方法对异步函数进行单元测试,javascript,unit-testing,ember.js,sinon,sinon-chai,Javascript,Unit Testing,Ember.js,Sinon,Sinon Chai,我正在尝试使用mocha和sinon.js为异步函数编写单元测试 下面是我的测试用例 describe('getOperations', function () { let customObj, store, someObj beforeEach(function () { someObj = { id: '-2462813529277062688' } store = { peekRecord: sandb
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不是对象上的函数。\u被调用方$
我正在测试的代码没有在任何地方调用store.query,而且我也有stubbed store.peekRecord,因此不确定如何调用它。您的getOperations函数使用异步语法,因此您需要在测试用例中使用async/Wait。而且,它工作得很好
例如。
索引
导出异步函数getOperationscustomObj,存储{
const obj=foocustombj,store;
返回obj;
}
导出函数foocustombj,store{
return store.peek recordobj,12345;
}
index.test.ts:
从导入{getOperations}./;
从信诺进口信诺;
从柴进口{expect};
描述59639661,=>{
描述开始操作,=>{
让顾客、商店、某物;
每个函数之前{
someObj={
id:-2462813529277062688,
};
存储={
peek记录:sinon.stub.returnssomeObj,
};
};
它应该通过,异步=>{
const obj=等待getOperationscustomObj,存储;
expectobj.to.deep.eqsomeObj;
};
};
};
100%覆盖率的单元测试结果:
59639661
获取操作
✓ 应该通过
1通过14毫秒
--------|-----|-----|-----|-----|----------|
文件|%Stmts |%Branch |%Funcs |%Lines |未覆盖的行|
--------|-----|-----|-----|-----|----------|
所有文件| 100 | 100 | 100 | 100 ||
index.test.ts | 100 | 100 | 100 | 100 ||
index.ts | 100 | 100 | 100 | 100 ||
--------|-----|-----|-----|-----|----------|
源代码:如果我必须在sinon.stub.returnssomeObj中添加一些功能,比如一些if语句,而不是直接返回对象,您能告诉我该怎么做吗。