And*_*rtz 10 unit-testing reactjs testing-library
我为选择编写了一个测试,并收到此警告。在我的测试中,我正在等待表演结束。为什么我会收到此错误?
警告:您似乎有重叠的 act() 调用,这是不支持的。在进行新的调用之前,请务必等待之前的 act() 调用。
test('Selection should be have the correct number of options', async () => {
const leftClick = { button: 0 };
const { options } = makeSUT();
const selection = screen.getByLabelText('MultiSelection');
// open all option
act(() => {
userEvent.click(selection, leftClick);
});
// await wait();
options.forEach(async (option, index) => {
if (index === 0) {
expect((await screen.findAllByText(option.label)).length).toEqual(1);
} else {
expect((await screen.findAllByText(option.label)).length).toEqual(1);
}
});
});
Run Code Online (Sandbox Code Playgroud)
谢谢
reu*_*nnn 11
userEvent
实用 API 方法不应包含在act()
. 建议这里不要这样做。相反,您可以只await
调用方法。执行操作后,您可以使用waitFor等待组件状态更新并运行您的断言。为了简化您的逻辑,我将用 a替换findBywaitFor
,getBy
这样您就不async
必将forEach()
.
您应该确保您的设置userEvent
正确(请参阅此处)
以下内容应该可以解决您的问题:
test('Selection should be have the correct number of options', async () => {
const user = userEvent.setup(); // Make sure to setup correctly.
const leftClick = { button: 0 };
const { options } = makeSUT();
const selection = screen.getByLabelText('MultiSelection');
// Wait for the userEvent to click:
await user.click(selection, leftClick);
waitFor(() => {
options.forEach((option, index) => {
if (index === 0) {
expect((screen.getAllByText(option.label)).length).toEqual(1);
} else {
expect((screen.getAllByText(option.label)).length).toEqual(1);
}
});
});
});
Run Code Online (Sandbox Code Playgroud)