I have a component which uses axios within componentDidMount to retrieve data from the server. When using Jest / Enzyme for unit testing the component, the tests fail with a network error.
How do I mock componentDidMount so that the axios call to the server does not happen?
The component in question uses React DnD and is a 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. If the load_data method was being passed in as a prop, I could simply set that prop to jest.fn(). However this is my top level component which does not receive any props.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With