2017-10-16 9 views
5

私のアプリケーションでは、私のルーターで使用されているナビゲーションガードの中で、vuex名前空間のゲッターを使って認証状態を確認しています。ゲッターは、ユーザーが認証されている場合、マジックアンダーレイチェックを行います。sinonjsでvuexゲッターをスタブする

リダイレクトが認証された状態で行われることを確認する単純な単体テストを作成したいと思います。私はゲッターを突き刺すことに固執している。

私のゲッターは以下の通りです:

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

マイ認証モジュールは以下の通りです:

export default { 
    namespaced: true, 
    state, 
    getters 
} 

そして、私の店は以下の通りです:

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

マイnaviguationガードは次のとおりです。

import store from '@/store' 

export default (to, from, next) => { 
    if (store.getters['authentication/isAuthenticated']) { 
    next() 
    return 
    } 

    next({name: 'login'}) 
} 

私はユニットテストと書いてきました: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

ありがとう!できます –

関連する問題