我正在使用Jest和Enzyme测试我的组件,但尽管遵循this article使用act
方法,但测试失败。
错误:
~ 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 behaviour the user would see in the browser. Learn more at https://reactjs.org/docs/test-utils.html#act
in Component (created by WrapperComponent)
in WrapperComponent
● Component › should render
expect(received).toBe(expected) // Object.is equality
Expected: "data"
Received: "loading"
组件及其测试:
import { mount } from 'enzyme';
import * as React from 'react';
import { act } from 'react-dom/test-utils';
const getData = async () => new Promise<string>((resolve) => resolve('data'));
const Component: React.FC = () => {
const [data, setData] = React.useState('');
const [isLoading, setIsLoading] = React.useState(true);
const onClick = async () => {
setIsLoading(true);
try {
const dataResponse = await getData();
setData(dataResponse);
} catch (error) {
console.error('getData failed', error);
}
setIsLoading(false);
};
return (
<button onClick={onClick}>
<p>{isLoading ? 'loading' : data}</p>
</button>
);
};
describe('Component', () => {
it('should render', () => {
const component = mount(<Component />);
const button = component.find('button');
const paragraph = component.find('p');
expect(button).toBeDefined();
expect(paragraph).toBeDefined();
expect(paragraph.props().children).toBe('loading');
void act(() => {
button.simulate('click');
});
expect(paragraph.props().children).toBe('data');
// test fails here ---------------------^^^^^^
});
});
1条答案
按热度按时间xqnpmsa81#
尝试 Package
button.simulate
//类似这样的东西