用 sinonjs 存根 vuex getters

Stubbing vuex getters with sinonjs

在我的应用程序中,在我的路由器使用的导航守卫中,我有一个 vuex 命名空间 getter 来检查身份验证状态。 getter 执行神奇的底层检查用户是否已通过身份验证。

我想编写一个简单的单元测试来检查重定向是否根据身份验证状态完成。我一直坚持 getter.

我的getter如下:

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

我的身份验证模块如下:

export default {
    namespaced: true,
    state,
    getters
}

我的店铺如下:

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

我的导航员是:

import store from '@/store'

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

  next({name: 'login'})
}

我写了那个单元测试:

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

单元测试触发以下错误:TypeError: Cannot redefine property: authentication/isAuthenticated

我尝试使用 authenticatedStub.value(false) 作为存根的替代方法,但错误是一样的。 我无法对 getter 进行存根以避免在保护测试中使用存储逻辑。

有人能在组件之外存根 getter 吗?

此致

问题是 vuex 将 getter 设置为不可配置的属性,因此无法更改。

对它们进行存根的一种方法是对 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')
  })
})