[英]Perform an integration test on a react component where the text input uses debounce (using react testing library)
我正在嘗試測試一個包含結果列表的反應組件,以及用戶可以輸入以過濾結果的文本輸入。 100 毫秒的去抖動用於在用戶鍵入時延遲過濾器。 去抖導致當前測試中斷:
test('typing ', async () => {
render(<PunkApi />);
await userEvent.type(textInput, 'nothing should show');
// * There is a delay here that I need to accommodate for
// Get table component and check that there are 0 results:
const table = await screen.findByRole('table');
const [tableHeader, tableBody] = within(table).getAllByRole('rowgroup');
expect(tableBody).toBeEmptyDOMElement(); // Error: received 15 results.
});
我可以通過包含 setTimeout/promise 來讓測試工作:
function delay(time: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, time));
}
// insert this line in the above test at the * location:
await act(() => delay(600));
所以我知道問題與我的測試/代碼的異步問題有關。 我知道處理這個問題的正確方法是jest.useFakeTimers()
而不是我捏造的 setTimeout/promise 解決方案。 但是當我嘗試實現時,我什至在更改測試之前就收到錯誤消息:
beforeAll(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
});
只要我包含jest.useFakeTimers();
行,我在運行測試時收到此錯誤:
thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
誰能幫我看看這應該如何工作?
感謝 Afsanefda 將我指向testing-library.com/docs/dom-testing-library/api-async/#waitfor async 文檔。
test('typing ', async () => {
render(<PunkApi />);
const buzzRow = await screen.findByText(/buzz/i); // ADDED THIS LINE: Initially there is a result with the word 'buzz' in it.
await userEvent.type(textInput, 'nothing should show');
// * There is a delay here that I need to accommodate for
// INSERT FOLLOWING LINE (waitForElementToBeRemoved, as per documentation):
await waitForElementToBeRemoved(emptyResultsMessage)
// Get table component and check that there are 0 results:
const table = await screen.findByRole('table');
const [tableHeader, tableBody] = within(table).getAllByRole('rowgroup');
expect(tableBody).toBeEmptyDOMElement(); // THIS NOW PASSES CORRECTLY
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.