我有一个使用反应路由器的组件,如下所示: _viewCompany(companyId) { this.context.router.push(`/admin/companies/${companyId}`);} 它在组件中运行良好,但在为组件编写测试时遇到了错误.这是导致问题的测
_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'); });
您甚至可以测试上下文对象.就像我上面做的那样.