我在类组件中有以下代码,我正在尝试测试 componentWillUnmount。
export class Hello extends React.PureComponent {
constructor(){
super();
this.isCLoseFromHeaderClicked = true;
}
componentWillUnmount() {
if(this.isCLoseFromHeaderClicked) { this.props.closeModal(); }
}
....do some other stuff...
}
我为它写了如下测试用例
describe('componentWillUnmount', () => {
it('componentWillUnmount should be called', () => {
wrapper = shallowWithIntl(<Hello {...props} />);
const componentWillUnmount = jest.spyOn(wrapper.instance(), 'componentWillUnmount');
wrapper.unmount();
expect(componentWillUnmount).toHaveBeenCalled();
});
});
此测试用例通过但覆盖率未达到要求。我还需要测试 else 部分
有谁知道我该如何测试 else 部分?
最佳答案
我会简单地尝试 wrapper.instance().isCloseFrom... = false
(在卸载之前)以测试未调用 closeModal
关于reactjs - 如何测试 componentWillUnmount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60582187/