测试组件时,我找不到如何调用useEffect挂钩。
我尝试了几种类似的解决方案,但是没有用:https://reactjs.org/docs/test-utils.html#act
我的组件:
const mapDispatchToProps = (dispatch: IDispatch, ownProps: ITextAreaOwnProps): ITextAreaDispatchProps => ({
onMount: () => dispatch(addTextArea(ownProps.id)),
});
export const TextArea = (props) => {
React.useEffect(() => {
props.onMount();
}, []);
// more code... //
return (
<>
<TextareaTagName
{...props.additionalAttributes}
className={props.className}
/>
{props.children}
{getValidationLabel()}
</>
);
};
我的测试:
it('should call prop onMount on mount', () => {
const onMount = jasmine.createSpy('onMount');
mount(<TextArea id="textarea-id" onMount={onMount} />);
expect(onMount).toHaveBeenCalledTimes(1);
});
简短的答案是您无法直接对其进行测试。基本上,您需要在组件中触发更改检测以激活useEffect挂钩。通过执行类似的操作,您可以轻松使用'react-dom / test-utils'库。
import { act } from 'react-dom/test-utils'; import { shallow, mount } from 'enzyme'; it('should call prop onMount on mount', () => { const onMount = jasmine.createSpy('onMount'); const wrapper = mount(<TextArea id="textarea-id" onMount={onMount} />); act(() => { wrapper.update(); }); expect(onMount).toHaveBeenCalledTimes(1);
});
关于文档,useEffect应该在任何属性更改时更新。