问题描述
我正在尝试测试是否调用了componentWillMount,为此我进行了测试
I am trying to test whether componentWillMount was called and for that my test is
test('calls `componentWillMount` before rendering', () => {
let fn = jest.fn(SomeComponent.prototype.componentWillMount)
mount(<SomeComponent />)
expect(fn).toHaveBeenCalled()
})
但是,即使调用componentWillMount方法,测试也不会通过.我在这里想念什么?
But even though the componentWillMount method is called, the test does not pass.What am I missing here?
推荐答案
我不知道其他答案是否对您的问题有所帮助,但您无需测试componentWillMount. React应该已经为您完成了该测试.
I don't know if the other answers have helped with your question, but you shouldn't need to test componentWillMount. React should already do that testing for you.
与您的测试更相关的是测试您在组件中使用该方法的功能或动作.
More relevant to your testing would be to test the functions or actions you are putting in that method for your component.
如果您要进行一些API调用,运行基于prop或其他任何功能的函数,那么这就是您应该测试的内容.模拟componentWillMount
触发的功能/动作/代码,并对此进行断言和期望.
If you are making some API call, running a function based on props, or anything else, that is what you should be testing for. Mock the function/action/code that componentWillMount
triggers, and make assertions and expectations on that.
示例:
组件:
class YourComponent extends Component {
componentWillMount() {
/*this fetch function is actually what you want to test*/
this.props.fetch('data')
}
render() {
/* whatever your component renders*/
}
}
测试:
test('should call fetch when mounted', () => {
let mockFetch = jest.fn()
const wrapper = mount(<SomeComponent fetch={mockFetch}/>);
expect(wrapper).toBeDefined();
expect(mockFetch).toHaveBeenCalled();
expect(mockFetch.mock.calls[0]).toEqual(['data'])
});
这篇关于如何使用玩笑和酶来监视componentWillMount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!