[英]Perform an integration test on a react component where the text input uses debounce (using react testing library)
I'm trying to test a react component that contains a list of results, and a text input that the user can type into in order to filter the results.我正在尝试测试一个包含结果列表的反应组件,以及用户可以输入以过滤结果的文本输入。 A 100ms debounce is used to delay the filter as the user types.
100 毫秒的去抖动用于在用户键入时延迟过滤器。 The debounce is causing the current test to break:
去抖导致当前测试中断:
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.
});
I can get the test to work by including a setTimeout/promise:我可以通过包含 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));
So I know the issue is to do with an async issue with my test/code.所以我知道问题与我的测试/代码的异步问题有关。 I understand that the correct way to handle this involves
jest.useFakeTimers()
instead of the setTimeout/promise solution I've fudged.我知道处理这个问题的正确方法是
jest.useFakeTimers()
而不是我捏造的 setTimeout/promise 解决方案。 But when I try to implement I get an error before I even change the test:但是当我尝试实现时,我什至在更改测试之前就收到错误消息:
beforeAll(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.clearAllTimers();
});
As soon as I include the jest.useFakeTimers();
只要我包含
jest.useFakeTimers();
line, I get this error when I run tests:行,我在运行测试时收到此错误:
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."
Can anyone help to show me how this is supposed to work?谁能帮我看看这应该如何工作?
Credit to Afsanefda for pointing me towards the testing-library.com/docs/dom-testing-library/api-async/#waitfor async documents.感谢 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.