模拟componentDidMount生命周期方法进行测试 [英] Mock componentDidMount lifecycle method for testing

查看:494
本文介绍了模拟componentDidMount生命周期方法进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,该组件使用componentDidMount中的axios从服务器检索数据.使用Jest/Enzyme对组件进行单元测试时,测试将失败,并出现网络错误.

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.

如何模拟componentDidMount,以便不会发生对服务器的axios调用?

How do I mock componentDidMount so that the axios call to the server does not happen?

有问题的组件使用 React DnD ,并且一个DragDropContext.

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);

示例测试:

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);
}

所以我只需要模拟componentDidMountload_data,这样它就不会尝试调用服务器.如果将load_data方法作为prop传入,则可以将该prop设置为jest.fn().但是,这是我的顶级组件,没有任何道具.

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.

推荐答案

默认情况下,Lifecyle方法不适用于浅表,您需要添加带有浅表的标记

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

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

在此之前,您可以在componentDidMount上创建间谍,以检查其名称是否为

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

const spyCDM = jest.spyOn(Board.prototype, 'componentDidMount');

并且为了防止axios请求到达服务器,您可以使用 moxios

and to prevent the axios request from hitting the server , you can mock the axios call using moxios

这篇关于模拟componentDidMount生命周期方法进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆