使用React和Enzyme测试异步处理程序中的中间状态



尽管阅读了酶和act的文档,但我找不到对我的用例的响应,因为示例只显示了简单的用例。

我有一个显示按钮的React组件。onClick处理程序设置加载布尔值并调用外部API。我想断言,当我们点击按钮时,组件显示了加载指示器。

这是组件:

export default function MyButton(): ReactElement {
const [loading, setLoading] = useState<boolean>(false);
const [data, setData] = useState<any>(null);
const onClick = async (): Promise<void> => {
setLoading(true);
const response = await fetch('/uri');
setData(await response.json());
setLoading(false);
};
if (loading) {
return <small>Loading...</small>;
}
return (
<div>
<button onClick={onClick}>Click Me!</button>
<div>
{data}
</div>
</div>
);
}

下面是测试:

test('should display Loading...', async () => {
window.fetch = () => Promise.resolve({
json: () => ({
item1: 'item1',
item2: 'item2',
}),
});
const component = mount(<MyButton />);
// Case 1 ✅ => validates the assertion BUT displays the following warning
component.find('button').simulate('click');
// Warning: An update to MyButton inside a test was not wrapped in act(...).
// When testing, code that causes React state updates should be wrapped into act(...):
// act(() => {
/* fire events that update state */
// });
/* assert on the output */
// This ensures that you're testing the behavior the user would see in the browser. Learn more at [URL to fb removed because SO does not accept it]
// Case 2 ❌ => fails the assertion AND displays the warning above
act(() => {
component.find('button').simulate('click');
});
// Case 3 ❌ => fails the assertion BUT does not display the warning
await act(async () => {
component.find('button').simulate('click');
});
expect(component.debug()).toContain('Loading...');
});

正如你所看到的,如果我摆脱了警告,我的测试就不再令人满意了,因为它在等待承诺的解决。在使用act时,我们如何断言中间状态的变化?

谢谢。

只需手动解决承诺:

const mockedData = {
json: () => ({
item1: 'item1',
item2: 'item2',
}),
};
let resolver;
window.fetch = () => new Promise((_resolver) => {
resolver = _resolver;
});
// ....
await act(async () => {
component.find('button').simulate('click');
});
expect(component.debug()).toContain('Loading...');
resolver(mockedData);
expect(component.debug()).not.toContain('Loading...');

PS,但为了可读性,我宁愿有两个单独的测试:一个是永远不会解析的new Promise();,另一个是自动解析的Promise.resolve(mockedData)

相关内容

  • 没有找到相关文章

最新更新