簡體   English   中英

禁用 Jest setTimeout 模擬

[英]Disable Jest setTimeout mock

我正在為依賴於 websocket 庫的代碼編寫 Jest 測試。

模擬了 websocket 庫。 我想發送一條消息,等待異步操作完成,然后檢查響應。

it('sends a message and gets a response', () => {
  processor(ws).sendMessage()  // do a bunch of async stuff, call websocket.sendMessage()
  setTimeout(() => {
    expect(ws.getResponse()).toEqual('all done')
  }, 100)
})

不幸的是,因為 Jest 模擬了 setTimeout,所以 setTimeout 失敗了。 如果我運行jest.runAllTimers() ,超時會立即發生,因此無法接收消息。

知道如何說服 jest 取消模擬 setTimeout 或 Jasmine 解決方法嗎?

您可以在測試用例之前添加以下代碼。 它適用於Jest v14.1.0 -

  jest.useRealTimers()

您不應該在測試期間等待(使用setTimeout )。 相反,請使用專為該用例設計的waitFor 它將繼續運行測試,直到通過或達到超時(默認為 1 秒)。 像這樣寫你的測試:

import {waitFor} from '@testing-library/react';

it('sends a message and gets a response', () => {
  processor(ws).sendMessage()`  // do a bunch of async stuff, call websocket.sendMessage()
  waitFor(() => {
    expect(ws.getResponse()).toEqual('all done');
  });
});

如果到超時結束時, expect仍然沒有通過,則測試將失敗。 如果期望在 0.01 秒內成功,則測試將不再需要繼續進行。

暫無
暫無

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

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