reactjs – React单元测试,无法读取未定义的反应路由器的“推送
发布时间:2020-12-15 09:34:53 所属栏目:百科 来源:网络整理
导读:我有一个使用反应路由器的组件,如下所示: _viewCompany(companyId) { this.context.router.push(`/admin/companies/${companyId}`);} 它在组件中运行良好,但在为组件编写测试时遇到了错误.这是导致问题的测试(我使用酶,jest,sinon): it('should call _view
我有一个使用反应路由器的组件,如下所示:
_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'); }); 您甚至可以测试上下文对象.就像我上面做的那样. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |