Ale*_*hen 5 javascript node.js async-await sinon
无法使用sinon和async/await运行此测试.这是我正在做的一个例子:
// in file funcs
async function funcA(id) {
let url = getRoute53() + id
return await funcB(url);
}
async function funcB(url) {
// empty function
}
Run Code Online (Sandbox Code Playgroud)
而且测试:
let funcs = require('./funcs');
...
// describe
let stubRoute53 = null;
let stubFuncB = null;
let route53 = 'https://sample-route53.com/'
let id = '1234'
let url = route53 + id;
beforeEach(() => {
stubRoute53 = sinon.stub(funcs, 'getRoute53').returns(route53);
stubFuncB = sinon.stub(funcs, 'funcB').resolves('Not interested in the output');
})
afterEach(() => {
stubRoute53.restore();
stubFuncB.restore();
})
it ('Should create a valid url and test to see if funcB was called with the correct args', async () => {
await funcs.funcA(id);
sinon.assert.calledWith(stubFuncB, url)
})
Run Code Online (Sandbox Code Playgroud)
通过console.log我已经验证funcA正在生成正确的URL,但是,我收到了错误AssertError: expected funcB to be called with arguments.当我尝试调用stubFuncB.getCall(0).args它时打印出null.所以也许是我对async/await缺乏了解,但我无法弄清楚为什么url没有被传递给那个函数调用.
谢谢
我认为你的funcs声明不正确.Sinon无法存根getRoute53并funcB调用内部funcA试试这个:
funcs.js
const funcs = {
getRoute53: () => 'not important',
funcA: async (id) => {
let url = funcs.getRoute53() + id
return await funcs.funcB(url);
},
funcB: async () => null
}
module.exports = funcsRun Code Online (Sandbox Code Playgroud)
tests.js
describe('funcs', () => {
let sandbox = null;
beforeEach(() => {
sandbox = sinon.createSandbox();
})
afterEach(() => {
sandbox.restore()
})
it ('Should create a valid url and test to see if funcB was called with the correct args', async () => {
const stubRoute53 = sandbox.stub(funcs, 'getRoute53').returns('https://sample-route53.com/');
const stubFuncB = sandbox.stub(funcs, 'funcB').resolves('Not interested in the output');
await funcs.funcA('1234');
sinon.assert.calledWith(stubFuncB, 'https://sample-route53.com/1234')
})
})Run Code Online (Sandbox Code Playgroud)
PS此外,使用沙箱.清理存根更容易
| 归档时间: |
|
| 查看次数: |
5968 次 |
| 最近记录: |