2017-10-16 10 views
5

내 응용 프로그램에서 내 라우터에서 사용하는 탐색 가드 내에서 인증 상태를 확인하는 vuex 네임 스페이스 게터가 있습니다. getter는 사용자가 인증되면 마법 밑받침 검사를 수행합니다.sinonjs를 사용하는 vuex 게터 스터브

리디렉션이 인증 된 상태에 따라 수행되는지 확인하는 간단한 단위 테스트를 작성하고 싶습니다. 나는 getter를 stubbing에 갇혀있어.

내 게터는 다음

isAuthenticated (state) { 
    return state.token !== null 
} 

내 인증 모듈은 다음과 같다 :

export default new Vuex.Store({ 
    modules: { 
     authentication 
    } 
}) 

내 naviguation 가드는 다음과 같습니다

export default { 
    namespaced: true, 
    state, 
    getters 
} 

그리고 내 가게 다음과 같다 :

내가 단위 테스트를 썼다했습니다 TypeError: Cannot redefine property: authentication/isAuthenticated :

describe('authenticated-guard.spec.js',() => { 
     let authenticatedStub 
     beforeEach(() => { 
     authenticatedStub = sandbox.stub(store.getters, 'authentication/isAuthenticated') 
     }) 

     afterEach(() => { 
     sandbox.restore() 
     }) 

     it('should redirect to login route when the user is not authenticated',() => { 
     // Given 
     const to = {} 
     const from = {} 
     const next = spy() 
     authenticatedStub.value(false) 

     // When 
     authenticatedGuard(to, from, next) 

     // Then 
     assert.ok(next.calledWith({name: 'login'}), 'should have redirected to login route') 
     }) 
    }) 

단위 테스트는 다음과 같은 오류를 트리거합니다.

authenticatedStub.value(false)을 사용하여 스텁의 대안으로 시도했지만 오류는 같습니다. 가드 테스트에서 스토어 로직을 사용하지 않으려면 스터핑 할 수 없습니다.

누군가가 구성 요소 밖의 게터를 스터핑 할 수 있습니까?

안부

답변

1

문제는 vuex 비 설정 속성으로 게터를 설정하고, 그래서 그들은 변경할 수 없다.

을 스텁 수있는 방법이 그래서 테스트는 다음과 같이 작동 할 수있는 getters 개체 자체를 스텁하는 것입니다

describe('authenticated-guard.spec.js',() => { 
    it('should redirect to',() => { 
    const authenticatedStub = sandbox.stub(store, 'getters') 
    // Given 
    const to = {} 
    const from = {} 
    const next = spy() 
    authenticatedStub.value({ 
     'authentication/isAuthenticated': false 
    }) 

    // When 
    authenticatedGuard(to, from, next) 

    // Then 
    expect(next.lastCall.args).to.deep.equal([{name: 'login'}], 'login route when the user is not authenticated') 

    authenticatedStub.value({ 
     'authentication/isAuthenticated': true 
    }) 

    authenticatedGuard(to, from, next) 

    expect(next.lastCall.args).to.deep.equal([], 'next route when the user is authenticated') 
    }) 
}) 
+0

감사합니다! 그것은 작동합니다. –