【发布时间】:2018-03-28 00:34:12
【问题描述】:
在我的应用程序中,在路由器使用的导航守卫内,我有一个 vuex 命名空间的 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 进行存根?
问候
【问题讨论】:
标签: unit-testing vue.js vuejs2 sinon vuex