2017-10-16 114 views
5

Uygulamamda, yönlendiricimin kullandığı bir gezinme muhafazasının içinde, kimlik doğrulama durumunu kontrol etmek için vuex adlandırılmış bir alıcım var. Kullanıcı kimliği doğrulanırsa getter sihirbazlık kontrolünü yapar.sinonjs ile Stubbing vuex getters

Yönlendirme işleminin doğrulanmış duruma göre yapıldığını kontrol eden basit bir birim testi yazmak istiyorum. Alıcıyı sarmak için sıkışıp kaldım.

Benim alıcı şudur:

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

Benim kimlik doğrulama modülü şudur:

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

Benim naviguation bekçi geçerli:

export default { 
    namespaced: true, 
    state, 
    getters 
} 

Ve deposunda takip ediyor:

import store from '@/store' 

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

    next({name: 'login'}) 
} 

Ben birim testi yazdım ettik: 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') 
     }) 
    }) 

birim test aşağıdaki hatayı tetikler.

authenticatedStub.value(false) kullanarak saplama alternatif olarak denedim, ancak hata aynıdır. Koruma testlerinde mağaza mantığından kaçınmak için alıcıyı kolayamıyorum.

Birisi bileşenlerin dışında herhangi bir alıcıya kolayabiliyor mu?

Selamlar

cevap

1

sorun o vuex olmayan yapılandırılabilir özellikler gibi alıcılar belirler, bu yüzden değiştirilemez.

onları saplama bir yolu böylece test böyle işe yarayabilir getters nesnenin kendisini saplama için geçerli:

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

teşekkürler! İşe yarıyor –