reactjs – React单元测试,无法读取未定义的反应路由器的“推送”

我有一个使用反应路由器的组件,如下所示:

_viewCompany(companyId) {
    this.context.router.push(`/admin/companies/${companyId}`);
}

它在组件中运行良好,但在为组件编写测试时遇到了错误.这是导致问题的测试(我使用酶,jest,sinon):

it('should call _viewCompany',() => {
        jest.spyOn(CompaniesList.prototype,'_viewCompany');
        wrapper = mount(<CompaniesList {...props}/>);
        const viewButton = wrapper.find('.btn-info').at(0);
        viewButton.simulate('click');
        expect(CompaniesList.prototype._viewCompany).toHaveBeenCalled();
    });

此测试返回错误,说明以下内容:

无法读取undefined属性’push’

我可以做些什么来模拟它或为测试创建一个空函数?

解决方法

您需要在安装组件时传递上下文对象.

function Router () {
   this.router = [];

   this.push = function(a) {
     this.router.push(a);
   };

   this.get = function(index){
      return this.router[index];
   }
    this.length = function(){
     return this.router.length;
   }
}

function History () {
   this.history = [];

   this.push = function(a) {
    this.history.push(a);
    };

    this.get = function(index){
     return this.history[index];
    }
   this.length = function(){
      return this.history.length;
   }
}

it('should call _viewCompany',() => {
    jest.spyOn(CompaniesList.prototype,'_viewCompany');
    wrapper = mount(<CompaniesList {...props}/>,{context:{router: new 
                Router(),history: new History()}});
    const viewButton = wrapper.find('.btn-info').at(0);
    viewButton.simulate('click');
    expect(CompaniesList.prototype._viewCompany).toHaveBeenCalled();
    expect(wrapper.context().router.length()).toEqual('1');
});

您甚至可以测试上下文对象.就像我上面做的那样.

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...