Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock componentDidMount lifecycle method for testing

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.

like image 581
darkpool Avatar asked Feb 14 '26 03:02

darkpool


1 Answers

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

like image 155
Alex Mutricy Avatar answered Feb 15 '26 17:02

Alex Mutricy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!