darkpool
darkpool

Reputation: 14641

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.

Upvotes: 3

Views: 8785

Answers (2)

Alex Mutricy
Alex Mutricy

Reputation: 83

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

Upvotes: 7

Shubham Khatri
Shubham Khatri

Reputation: 281646

Lifecyle methods do not defaultly work with shallow, you need to add a flag with shallow

 const board = shallow(<Board />, { lifecycleExperimental: true });

Before that you can create a spy on componentDidMount to check if it was called like

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

Upvotes: 4

Related Questions