我有一个使用组件axios内componentDidMount从服务器获取数据。使用 Jest / Enzyme 对组件进行单元测试时,测试失败并出现网络错误。
我如何模拟componentDidMount以使axios对服务器的调用不会发生?
有问题的组件使用React DnD并且是一个DragDropContext.
class Board extends Component {
componentDidMount() {
this.load_data();
}
load_data = () => {
// axios server calls here
}
}
export default DragDropContext(HTML5Backend)(Board);
示例测试:
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);
}
所以我只需要模拟componentDidMount或load_data这样它就不会尝试调用服务器。如果该load_data方法作为props传入,我可以简单地将该props设置为jest.fn(). 然而,这是我没有收到任何props的顶级组件。