在React组件中,我有
export default class MyComp extends Component {
...
componentDidMount() {
this.customFunc();
}
customFunc = () => {
// ..
}
...
}
Run Code Online (Sandbox Code Playgroud)
当我尝试像这样用Jest和Enzyme测试这种方法时:
it('Should call customFunc on mount', () => {
const MyCompInstance = mount(<MyComp {...props} >).instance();
const spy = jest.spyOn(MyCompInstance, 'customFunc');
expect(spy).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
它失败了 Expected mock function to have been called, but it was not called.
有趣的是,如果我把console.log()在componentDidMount和中custsomFunc-它们被调用。我究竟做错了什么?
PS:我forceUpdate在实例上尝试了该实例,就在期望值之前,但是仍然遇到相同的错误。