我正试图从我的vuex商店测试以下非常简单的getter。它只是连接两个字符串:
const getters = {
adressToGet: state => {
return state.baseAdress + store.getters.queryToGet
}
}
模仿状态部分很容易,但我找不到一个模拟商店的好方法。
如果这是在组件中,我可以使用mount
或shallow
挂载组件并为其分配模拟存储,但事实并非如此。这是来自vuex商店。
这是我的测试代码:
import Search from '@/store/modules/search'
jest.mock('@/store/modules/search.js')
describe('search.js', () => {
test('The adress getter gets the right adress', () => {
const state = {
baseAdress: 'http://foobar.com/'
}
// I define store here, but how can I inject it into my tested getter ?
const store = {
getters: {
queryToGet: 'barfoo'
}
}
expect(Search.getters.adressToGet(state)).toBe('http://foobar.com/barfoo')
})
})
我得到http://foobar.com/undefined
而非预期。
最好的方法是什么?
编辑:在第一条评论之后,我的新版本,但它仍然提供相同的结果:
import Search from '@/store/modules/search'
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
jest.mock('@/store/modules/search.js')
describe('search.js', () => {
test('The adress getter gets the right adress', () => {
const localVue = createLocalVue()
localVue.use(Vuex)
const mockState = {
baseAdress: 'http://foobar.com/'
}
const store = new Vuex.Store({
state: mockState,
getters: {
queryToGet: function () {
return 'barfoo'
}
}
})
expect(Search.getters.adressToGet(mockState))
.toBe('http://foobar.com/barfoo')
})
})
答案 0 :(得分:2)
经过大量研究,我意识到我不得不用Jest模仿商店的依赖性。这似乎是正确的方法并通过测试:
import Search from '@/store/modules/search'
jest.mock('@/store/index.js', () =>({
getters: {
queryToGet: 'barfoo'
}
}))
jest.mock('@/store/modules/search.js')
describe('search.js', () => {
test('The adress getter gets the right adress', () => {
const state = {
baseAdress: 'http://foobar.com/'
}
expect(Search.getters.adressToGet(state))
.toBe('http://foobar.com/barfoo')
})
})