gpt4 book ai didi

reactjs - 为什么我需要将 React/Enzyme 状态更改包装在 act 中?

转载 作者:行者123 更新时间:2023-12-03 16:56:55 25 4
gpt4 key购买 nike

在我简单的 React/ReactDOM/Enzyme 单元测试中,我收到了来自 ReactDOM 的警告,关于将任何突变包装到 act() 中的状态。 .如果我的测试仍然通过,为什么我需要这样做?我有 50 个左右的 React 组件,它们都使用钩子(Hook)、自定义钩子(Hook)等,我从不包裹 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

最佳答案

act()首先运行所有相关的useEffect否则那将是异步的方式。您没有看到任何区别,因为您没有 useEffect在您的组件代码中
根据Enzyme's docs在最新版本中 mount()应该已经用 act() 包裹了内部:

If you're using React 16.8+ and .mount(), Enzyme will wrap apis including .simulate(), .setProps(), .setContext(), .invoke() with ReactTestUtils.act() so you don't need to manually wrap it.

We cannot wrap the result of .prop() (or .props()) with .act() in Enzyme internally since it will break the equality of the returned value. However, you could use .invoke() to simplify the code:

const wrapper = mount(<SomeComponent />);
wrapper.invoke('handler')();
expect(/* ... */);```

关于reactjs - 为什么我需要将 React/Enzyme 状态更改包装在 act 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com