2017-03-09 2 views
2

내가 지금처럼 라우터를 반응 사용하는 구성 요소가 읽을 수 없습니다, 단위 테스트 반응 :는 정의의 '푸시'반응 라우터

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

그것은 구성 요소에서 잘 작동하지만, 구성 요소에 대한 테스트를 쓰는 동안 내가 달릴 오류로. 여기에 (I 효소, 농담, 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

내가 할 수있는 일이 있습니까 그것을 조롱하거나 테스트를 위해 빈 함수를 만드시겠습니까?

답변

0

구성 요소를 탑재하는 동안 컨텍스트 개체를 전달해야합니다.

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

컨텍스트 개체도 테스트 할 수 있습니다. 내가 위에서 한 것처럼.