这是我的JEST测试用例。我将状态更改操作 Package 到act
中。但它没有帮助。
it('ListInput add item', done => {
const valueTyped = '123.1.1.1';
const formItemDataPath = ['proxy', 'rules', 'excludedAddresses'];
let listInputInternalInput;
let listInputAddItemButton;
let c;
let formValue;
const handleFormChange = v => {
formValue = v;
};
act(() => {
const ListInputForm = () => {
return (
<div>
<BasicForm initialValue={clone(bondingFormData)} onChange={handleFormChange}>
<BasicFormItem name={formItemDataPath} label={'listInput'}>
<ListInput data-testid='listInput' />
</BasicFormItem>
</BasicForm>
</div>
);
};
const { container } = render(<ListInputForm />);
c = container;
});
listInputInternalInput = c!.querySelector('Input');
listInputAddItemButton = c!.querySelector('[type=button]');
act(() => {
fireEvent.change(listInputInternalInput, { target: { value: valueTyped } });
fireEvent.click(listInputAddItemButton);
});
//
setTimeout(() => {
expect(getProperty(formValue!, formItemDataPath)).toEqual([
...getProperty(bondingFormData, formItemDataPath),
valueTyped,
]);
done();
}, 1000);
});
字符串
我仍然看到一条警告消息:
at recipe (.../BasicForm.tsx:29:17)
console.error
Warning: An update to BasicForm 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/link/wrap-tests-with-act
at BasicForm (.../BasicForm.tsx:65:11)
at div
at ListInputForm
型
现在测试通过了,但是如果我删除setTimeout
的话会失败。所以我想要两件事:去掉警告和设置错误。任何想法都值得高度赞赏。
1条答案
按热度按时间tjrkku2a1#
要摆脱警告消息和
setTimeout
,您可以尝试使用async/await
沿着waitFor
函数,以确保所有状态更新都正确地 Package 在act()
中。下面是相同的代码:字符串