簡體   English   中英

Nodejs:使用 sinon 和 async/await 進行測試

[英]Nodejs: Testing with sinon and async/await

無法使用 sinon 和 async/await 運行此測試。 這是我正在做的一個例子:

// in file funcs
async function funcA(id) {
    let url = getRoute53() + id
    return await funcB(url);
}

async function funcB(url) {
    // empty function
}

和測試:

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)
})

通過console.log我已經驗證funcA正在生成正確的 URL,但是,我收到錯誤AssertError: expected funcB to be called with arguments 當我嘗試調用stubFuncB.getCall(0).args它會打印出 null。 所以也許是我對 async/await 缺乏了解,但我無法弄清楚為什么沒有將 url 傳遞給該函數調用。

謝謝

我認為您的 funcs 聲明不正確。 Sinon 無法存根getRoute53funcB調用的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 = funcs

測試.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') }) })

PS另外,使用沙箱。 更容易清潔存根

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM