【问题标题】:React unit testing, cannot read 'push' of undefined react router反应单元测试,无法读取未定义反应路由器的“推送”
【发布时间】:2017-07-30 23:08:59
【问题描述】:

我有一个像这样使用反应路由器的组件:

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

它在组件中运行良好,但是在为组件编写测试时遇到了错误。这是导致问题的测试(我正在使用酵素,开玩笑,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();
    });

此测试返回一个错误,内容如下:

Cannot read property 'push' of undefined

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

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2020-02-05
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      • 2017-11-01
      相关资源
      最近更新 更多