reactjs - 使用 Test Renderer 测试多个 React 组件状态更改
问题描述
我要测试的组件的状态isSubmitting
在我们尝试提交表单时设置为 true,然后在我们收到来自服务器的响应时设置回 false。
我想在每次状态更新后测试组件的状态。
const Component = () => {
const [isSubmitting, setIsSubmitting] = useState();
const handlePress = async () => {
setIsSubmitting(true);
await submitForm();
setIsSubmitting(false);
};
return (
<>
<button onPress={() => this.handlePress} />
{isSubmitting && <IsSubmitting />}
</>
)
}
我只能测试第一个组件状态,例如。当我将 isSubmitting 更新为 true 时。
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();
});
之后如何检查 IsSubmitting 组件是否隐藏?我也收到了一个错误,因为没有将更新包装到 act() 中。
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:104
Warning: An update to Component 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 https://reactjs.org/docs/test-utils.html#act
in Component
解决方案
我不得不两次调用 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([]);'
这样,我就可以在两种状态下测试组件。
推荐阅读
- eclipse - Eclipse 文件缺少文件夹,并且在源代码中缺少
- ios - 在 swift 错误 TIC 读取状态下解析 Api
- spring - Avoid duplicate code in criteria builder query in spring data jpa
- swift3 - 当我在 Tableview 中加载我的 json 时,我发现无法转换类型值的错误
- vue.js - vuejs点击测试鼠标事件
- c# - DataGridViewButtonCell 需要两次点击才能触发事件
- xamarin - Prism Navigation 在导航到其他页面后保留 MasterPageDetail 菜单
- pygsheets - 没有空值的pygsheet工作表大小
- azure - 使用 Azure 服务结构设置 Azure Function 代理
- excel - 表扩展而不是创建