cle*_*let 6 unit-testing sinon vue.js vuex vuejs2
在我的应用程序中,在我的路由器使用的导航防护装置内,我有一个vuex命名空间的getter来检查身份验证状态.如果用户已通过身份验证,则getter会执行神奇的底层检查.
我想编写一个简单的单元测试,检查重定向是否根据经过身份验证的状态完成.我被困在叮叮当当的吸气鬼身上.
我的吸气者如下:
isAuthenticated (state) {
return state.token !== null
}
Run Code Online (Sandbox Code Playgroud)
我的身份验证模块如下:
export default {
namespaced: true,
state,
getters
}
Run Code Online (Sandbox Code Playgroud)
我的商店如下:
export default new Vuex.Store({
modules: {
authentication
}
})
Run Code Online (Sandbox Code Playgroud)
我的导航卫士是:
import store from '@/store'
export default (to, from, next) => {
if (store.getters['authentication/isAuthenticated']) {
next()
return
}
next({name: 'login'})
}
Run Code Online (Sandbox Code Playgroud)
我写过单元测试:
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')
})
})
Run Code Online (Sandbox Code Playgroud)
单元测试会触发以下错误:TypeError: Cannot redefine property: authentication/isAuthenticated.
我已尝试使用存根作为替代,authenticatedStub.value(false)但错误是相同的.我无法存取吸气剂以避免在防护测试中存储逻辑.
有人能够在组件之外存在任何吸气剂吗?
问候
问题是 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')
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
465 次 |
| 最近记录: |