Stable vuex getters with sinons

In my application, inside the security navigation device used by my router, I have a vuex namespaced getter to check the authentication status. The getter performs a magical check of the litter if the user is authenticated.

I want to write a simple unit test that verifies that the redirect is performed according to the authenticated state. I'm stuck in biting a getter.

My recipient is as follows:

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

My authentication module is as follows:

 export default { namespaced: true, state, getters } 

And my store is as follows:

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

My guard:

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

I wrote that unit test:

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

unit test raises the following error: TypeError: Cannot redefine property: authentication/isAuthenticated .

I tried as an alternative to stub using authenticatedStub.value(false) , but the error is the same. I cannot drown out the getter so as not to store the storage logic in security tests.

Can anyone drown out any recipient outside the components?

Hello

+5
source share
1 answer

The problem is that vuex sets getters as non-configurable properties, so they cannot be changed.

The way to stub them is to stub the getters object getters , so that your test can work as follows:

 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') }) }) 
+1
source

Source: https://habr.com/ru/post/1272662/


All Articles