Sam*_*ure 4 vue.js jestjs vuex
我正在尝试从我的 vuex 商店测试以下非常简单的 getter。它只是连接两个字符串:
const getters = {
adressToGet: state => {
return state.baseAdress + store.getters.queryToGet
}
}
Run Code Online (Sandbox Code Playgroud)
嘲笑州部分很容易,但我找不到嘲笑商店的好方法。
如果这是在一个组件中,我可以使用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')
})
})
Run Code Online (Sandbox Code Playgroud)
我得到的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')
})
})
Run Code Online (Sandbox Code Playgroud)
经过大量研究,我意识到我必须用 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')
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7794 次 |
| 最近记录: |