[英]Mock componentDidMount lifecycle method for testing
I have a component which uses axios
within componentDidMount
to retrieve data from the server. 我有一个使用组件
axios
内componentDidMount
从服务器获取数据。 When using Jest / Enzyme for unit testing the component, the tests fail with a network error. 当使用Jest / Enzyme对组件进行单元测试时,测试会因网络错误而失败。
How do I mock componentDidMount
so that the axios
call to the server does not happen? 如何模拟
componentDidMount
以便不会发生对服务器的axios
调用?
The component in question uses React DnD and is a DragDropContext
. 有问题的组件使用React DnD并且是
DragDropContext
。
class Board extends Component {
componentDidMount() {
this.load_data();
}
load_data = () => {
// axios server calls here
}
}
export default DragDropContext(HTML5Backend)(Board);
Example test: 示例测试:
it('should do something', () => {
const board = shallow(<Board />);
// get the boardInstance because board is wrapped in Reactdnd DragDropContext
const boardInstance = board.dive().instance();
boardInstance.callSomeMethodToTestIt();
expect(testSomething);
}
So I just need to mock componentDidMount
or load_data
so that it doesn't try to call the server. 所以我只需要模拟
componentDidMount
或load_data
这样它就不会尝试调用服务器。 If the load_data
method was being passed in as a prop, I could simply set that prop to jest.fn()
. 如果
load_data
方法作为prop传入,我可以简单地将该prop设置为jest.fn()
。 However this is my top level component which does not receive any props. 然而,这是我的顶级组件,没有任何道具。
Lifecyle methods do not defaultly work with shallow, you need to add a flag with shallow Lifecyle方法默认不用浅,你需要添加一个浅的标志
const board = shallow(<Board />, { lifecycleExperimental: true });
Before that you can create a spy on componentDidMount
to check if it was called like 在此之前,您可以在
componentDidMount
上创建一个间谍来检查它是否被调用
const spyCDM = jest.spyOn(Board.prototype, 'componentDidMount');
and to prevent the axios request from hitting the server , you can mock the axios call using moxios
并且为了防止axios请求命中服务器,您可以使用
moxios
模拟axios调用
With the new update to enzyme, lifecycle methods are enabled by default. 随着酶的新更新,默认情况下启用生命周期方法。 ( https://airbnb.io/enzyme/docs/guides/migration-from-2-to-3.html#lifecycle-methods )
( https://airbnb.io/enzyme/docs/guides/migration-from-2-to-3.html#lifecycle-methods )
However, you can disable them in with shallow rendering as such: 但是,您可以使用浅渲染禁用它们:
const board = shallow(<Board />, { disableLifecycleMethods: true });
docs: https://airbnb.io/enzyme/docs/api/shallow.html#shallownode-options--shallowwrapper docs: https : //airbnb.io/enzyme/docs/api/shallow.html#shallownode-options--shallowwrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.