亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Sinon JS 測試異步函數?

如何使用 Sinon JS 測試異步函數?

月關寶盒 2022-12-29 13:51:45
下面是我想要實現的一個最小示例:fn3()如果異步函數已fn2()解析(調用時fn1),我想測試被調用的情況。但是我以某種方式未能使用sinon的存根語法做到這一點。我想知道我誤解了什么。// System Under Testexport function fn1() {    fn2().then(() => {        fn3();    });}export async function fn2() {    return new Promise((resolve, reject) => {        // expensive work        resolve();    });}export function fn3() {    console.log("fn3");}// Testimport * as Page from "xxx";it("test async", () => {    // stub this async to isolate the SUT    sinon.stub(Page, "fn2").resolves();    const stub = sinon.stub(Page, "fn3");    Page.fn1();    sinon.assert.calledOnce(stub);});/*    AssertError: expected fn3 to be called once but was called 0 times      276 |         Page.fn1();      277 |    > 278 |         sinon.assert.calledOnce(stub);          |                      ^      279 |     });      280 | });      at Object.fail (node_modules/sinon/lib/sinon/assert.js:107:21)      at failAssertion (node_modules/sinon/lib/sinon/assert.js:66:16)      at Object.calledOnce (node_modules/sinon/lib/sinon/assert.js:92:13)      at Object.<anonymous> (src/test.test.tsx:278:22)*/
查看完整描述

1 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

正如@jonrsharpe 所建議的那樣,根據 JavaScript 的“單線程、事件循環”性質,您sinon.assert.calledOnce(stub);將在解決(即調用)fn2內部承諾之前被調用。這里有一篇文章供參考:https ://dev.to/lydiahallie/javascript-visualized-promises-async-await-5gke 。Page.fn1.then(() => { fn3(); })


您可以嘗試將代碼更改為:


    ...


    return Page.fn1().then(() => {

      sinon.assert.calledOnce(stub);

    });

    

    ...

要么


it("test async", async () => {

    // stub this async to isolate the SUT

    sinon.stub(Page, "fn2").resolves();

    const stub = sinon.stub(Page, "fn3");


    await Page.fn1();


    sinon.assert.calledOnce(stub);

});

所以在解決sinon.assert.calledOnce(stub);后會被調用Page.fn1()。


查看完整回答
反對 回復 2022-12-29
  • 1 回答
  • 0 關注
  • 84 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號