【发布时间】:2021-04-23 10:55:28
【问题描述】:
我有一个问题困扰着我,我不知道如何解决这个问题。我有一个非常简单的 React Hooks 功能组件,它使用 useState 钩子,但是我在为它编写测试用例时遇到了问题(开玩笑),使用 @testing-library/react。
这是组件的主要内容:
// MyComponent.jsx
import InputComponent from '/some/folder/InputComponent';
...
export function MyComponent() {
const [randomStateVariable, setRandomStateVariable] = useState('');
...
const handleChange = value => setRandomStateVariable(value);
...
return (
<InputComponent
handleChange={handleChange}
input={{
value: randomStateVariable || ''
}}
/>
);
}
然后对于我的单元测试文件,我正在执行以下操作:
// MyComponent.test.js
import renderer from 'react-test-renderer';
import { render } from '@testing-library/react';
...
import MyComponent from 'MyComponent';
...
it('runs handleChange', () => {
const props = {
actions: {
someAction: jest.fn()
},
input: 'some input value'
};
...
const component = renderer.create(<MyComponent {...props} />);
const inputSelect = component.root.findByType(InputComponent).props;
inputSelect.handleChange(props.input);
expect(props.actions.someAction).toHaveBeenCalledWith(props.input);
});
现在,测试都通过了(我在文件中的其他测试用例中使用@testing-library/react),但是在运行测试套件时出现以下错误:
When testing, code that causes React state updates should be wrapped into act(...):
我不知道如何纠正这个问题。我没有安装@testing-library/react-hooks 包,我不确定应该从哪里导入act。我应该为此使用react-test-renderer,并从该包中导入act,还是应该从@testing-library/react 导入它?
我不知道如何编写测试用例,或修改现有测试用例,使用act,以摆脱控制台错误。有没有人可以提供帮助,或者为我指出正确的方向?
非常感谢!
【问题讨论】:
-
你在哪里调用
someAction函数?
标签: reactjs jestjs react-hooks react-testing-library react-state