我要测试的组件的状态为DEFAULT
,当我们尝试提交表单时将其设置为true,然后在收到服务器的响应时将其设置为false。
我想在每次状态更新后测试组件的状态。
isSubmitting
我只能测试第一个组件状态。当我更新isSubmitting为true时。
const Component = () => {
const [isSubmitting, setIsSubmitting] = useState();
const handlePress = async () => {
setIsSubmitting(true);
await submitForm();
setIsSubmitting(false);
};
return (
<>
<button onPress={() => this.handlePress} />
{isSubmitting && <IsSubmitting />}
</>
)
}
如何检查IsSubmitting组件之后是否被隐藏?我也因为不将更新包装到act()中而出现错误。
import React from 'react';
import { act, create } from 'react-test-renderer';
import Component from './Component';
it('shows loading screen after submit, and hides it after', async () => {
jest.spyOn(form, 'submitForm').mockResolvedValue();
const wrapper = create(<Component />);
act(() => {
wrapper.root.findByType(Button).props.onPress();
});
expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();
});
答案 0 :(得分:0)
我不得不两次调用act函数。第一次没有等待,第二次有了异步等待。
const wrapper = create(<Component />);
act(() => {
wrapper.root. findByType(Button).props.onPress();
});
expect(wrapper.root.findByType(IsSubmitting)).toBeDefined();
await act(async () => {});
expect(wrapper.root.findAllByType(IsSubmitting)).toStrictEqual([]);'
这样,我可以在两种状态下测试组件。