gpt4 book ai didi

unit-testing - 用 sinonjs stub vuex getters

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:33 24 4
gpt4 key购买 nike

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

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

我的 setter/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) 作为 stub 的替代方法,但错误是相同的。我无法对 getter 进行 stub 以避免在保护测试中使用存储逻辑。

是否有人能够在组件之外 stub 任何 setter/getter ?

问候

最佳答案

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

对它们进行 stub 的一种方法是对 getters 对象本身进行 stub ,这样您的测试就可以像这样工作:

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

关于unit-testing - 用 sinonjs stub vuex getters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46771146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com