簡體   English   中英

開玩笑的嘲笑諾言方法被稱為錯誤的次數

[英]jest mocking promise method called wrong number of times

作為我的redux動作的一部分,它發出了幾個順序的api請求。 apiCall方法返回帶有一些值的Promise,隨后的apiCall使用該值發出另一個請求,依此類推。 我正在使用Jest測試這些api調用。

 const myAPI = { apiCall(param: any): Promise<any> { return new Promise((resolve, reject) => { resolve('result'); }); }, }; const serialAPIRequests = () => { myAPI.apiCall('first_param') .then((result) => { console.log(result); return myAPI.apiCall(result); }) .then((result) => { console.log(result); return myAPI.apiCall(result); }) .then((result) => { console.log(result); return Promise.resolve(result); }); }; 

我試圖編寫一個測試以確保apiCall已被調用正確的次數並具有正確的參數。

 describe.only('my test', () => { it('should test api stuff', () => { myAPI.apiCall = jest.fn() .mockReturnValueOnce(Promise.resolve('result1')) .mockReturnValueOnce(Promise.resolve('result2')) .mockReturnValueOnce(Promise.resolve('result3')); serialAPIRequests(); expect(myAPI.apiCall).toHaveBeenCalledTimes(3); }); }); 

發生的事情是,Jest report Expected mock function to have been called three times, but it was called one time.

開玩笑的測試結果表明

  ● Console

console.log 
  result1
console.log 
  result2
console.log 
  result3

 ● my test › should test api stuff

expect(jest.fn()).toHaveBeenCalledTimes(3)

Expected mock function to have been called three times, but it was called one time.

console.log顯示不同值的事實意味着模擬返回已通過模擬函數正確傳遞,並且被調用了3次。

是什么原因造成的?如何正確測試此功能?

承諾是異步的,因此當您檢查該模擬實際上被調用過一次時,就可以了。

您可以這樣做。 等待所有調用完成並返回承諾以表明測試是異步的。

return serialAPIRequests().then(() => {
    expect(myAPI.apiCall).toHaveBeenCalledTimes(3);
})

使用async / await測試異步代碼。 在此處閱讀更多信息: https : //facebook.github.io/jest/docs/en/tutorial-async.html

describe.only('my test', () => {
      it('should test api stuff', async () => {
        myAPI.apiCall = jest.fn()
          .mockReturnValueOnce(Promise.resolve('result1'))
          .mockReturnValueOnce(Promise.resolve('result2'))
          .mockReturnValueOnce(Promise.resolve('result3'));
        await serialAPIRequests();
        expect(myAPI.apiCall).toHaveBeenCalledTimes(3);
      });
    });

暫無
暫無

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

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