【发布时间】:2020-01-27 08:16:00
【问题描述】:
在我的简单 React/ReactDOM/Enzyme 单元测试中,我收到了来自 ReactDOM 的警告,关于将任何突变包装到 act() 中的状态。如果我的测试仍然通过,为什么我需要这样做?我有 50 个左右的 React 组件,它们都使用钩子、自定义钩子等,我从不包裹 act(),它们都通过了。
我可以禁用此警告吗?我不想添加似乎没有理由的额外代码。
警告:
Warning: An update to MyComponent 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 [redacted]
我的测试:
const App = () => {
const [isLoaded, setIsLoaded] = useState(false);
const myOnClick = () => {
setIsLoaded(true);
};
return (
<div onClick={myOnClick}>
{isLoaded ? 'Yes' : 'No'}
</div>
)
}
describe('My test', () => {
let wrapper
beforeAll(() => {
wrapper = mount(<App />)
})
it('renders "no"', () => {
expect(wrapper.text()).toBe('No')
})
describe('When onClick is called', () => {
beforeAll(() => {
wrapper.find('div').prop('onClick')()
})
it('renders "yes"', () => {
expect(wrapper.text()).toBe('Yes')
})
})
})
CodeSandbox 重现:https://codesandbox.io/s/react-169-act-warning-repro-olm8o?expanddevtools=1&fontsize=14&hidenavigation=1&previewwindow=tests
【问题讨论】:
标签: reactjs jestjs enzyme react-dom