I'm trying to test the following very simple getter from my vuex store. It is simply concatenating two strings :
const getters = {
adressToGet: state => {
return state.baseAdress + store.getters.queryToGet
}
}
Mocking the state part is easy but I can't find a good way to mock the store.
If this was in a component, I could mount the component with mount or shallow and assign to it the mock store, but it isn't. This is from the vuex store.
This is my test code :
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')
})
})
I get http://foobar.com/undefined instead of expected.
What would be the best way to do this ?
Edit: Following the first comment, my new version, but it still gives the same result:
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')
})
})
After much research, I realized I had to mock the store dependency with Jest. This seems the correct way to do it and pass the test:
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')
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With