Mock componentDidMount lifecycle method for testing

半腔热情 提交于 2019-12-10 18:28:47

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/50344545/mock-componentdidmount-lifecycle-method-for-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!