Jest/Enzyme |在 componentDidMount 中测试函数调用
Jest/Enzyme | Test a function call in componentDidMount
在 componentDidMount()
React 生命周期方法上,当你想测试一个函数是否被调用时该怎么做。基本上组件代码如下所示:
state = {
randomStateToPopulate: []
};
// Test componentDidMount
componentDidMount() {
this.randomFunction();
}
randomFunction= () => {
listRandomData().then(({ data }) => {
this.setState({ randomStateToPopulate: data });
});
};
那么,你如何实际测试这个案例?
这是您要测试的案例场景。如果正在调用 componentDidMount,请检查它是否仅被调用一次,或者您想要调用多少次。
你的测试。 I have the explanation in comments below
// Inside your general `Describe`
let wrapper;
const props = {
// Your props goes here..
};
beforeEach(() => {
wrapper = shallow(<YourComponent {...props} />);
});
it('should check `componentDidMount()`', () => {
const instance = wrapper.instance(); // you assign your instance of the wrapper
jest.spyOn(instance, 'randomFunction'); // You spy on the randomFunction
instance.componentDidMount();
expect(instance.randomFunction).toHaveBeenCalledTimes(1); // You check if the condition you want to match is correct.
});
你可以抽象,这个案例做更复杂的事情,但它的基本要点是上面的。如果您有更详细或更好的解决方案,请 post 吧。谢谢!!
在 componentDidMount()
React 生命周期方法上,当你想测试一个函数是否被调用时该怎么做。基本上组件代码如下所示:
state = {
randomStateToPopulate: []
};
// Test componentDidMount
componentDidMount() {
this.randomFunction();
}
randomFunction= () => {
listRandomData().then(({ data }) => {
this.setState({ randomStateToPopulate: data });
});
};
那么,你如何实际测试这个案例?
这是您要测试的案例场景。如果正在调用 componentDidMount,请检查它是否仅被调用一次,或者您想要调用多少次。
你的测试。 I have the explanation in comments below
// Inside your general `Describe`
let wrapper;
const props = {
// Your props goes here..
};
beforeEach(() => {
wrapper = shallow(<YourComponent {...props} />);
});
it('should check `componentDidMount()`', () => {
const instance = wrapper.instance(); // you assign your instance of the wrapper
jest.spyOn(instance, 'randomFunction'); // You spy on the randomFunction
instance.componentDidMount();
expect(instance.randomFunction).toHaveBeenCalledTimes(1); // You check if the condition you want to match is correct.
});
你可以抽象,这个案例做更复杂的事情,但它的基本要点是上面的。如果您有更详细或更好的解决方案,请 post 吧。谢谢!!