繁体   English   中英

对文本输入使用去抖动的 React 组件执行集成测试(使用 React 测试库)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM