direct-vuex
direct-vuex copied to clipboard
Create multiple instances of vuex
Hi Paleo,
Thanks for this great library and the great docs!
I'm using Jest for unit testing and I'm realizing that the way direct-vuex is recommended in README.md may create issues during parallelized tests.
When setting a sample app like this:
// src/store/index.ts
const {
store,
rootActionContext,
moduleActionContext,
rootGetterContext,
moduleGetterContext
} = createDirectStore({
// … store implementation here …
})
// Export the direct-store instead of the classic Vuex store.
export default store
// The following exports will be used to enable types in the
// implementation of actions and getters.
export {
rootActionContext,
moduleActionContext,
rootGetterContext,
moduleGetterContext
}
// src/main.ts
import Vue from "vue"
import store from "./store"
new Vue({
store: store.original, // Inject the classic Vuex store.
// …
}).$mount("#app")
// tests/unit/MyComponentUsingAStore.spec.ts
import { shallowMount } from '@vue/test-utils'
import MyComponentUsingAStore from '@/components/MyComponentUsingAStore.vue'
describe('MyComponentUsingAStore.vue', () => {
it('Test 1', () => {
const wrapper = shallowMount(MyComponentUsingAStore)
expect(wrapper.find('.loading').text()).toEqual("Loading...")
})
it('Test 2', () => {
const wrapper = shallowMount(MyComponentUsingAStore)
expect(wrapper.find('.loading').text()).toEqual("Loading...")
})
})
Jest is running its tests in parallel. So, this scenario can generates errors :
- [Test 1] When mounting
MyComponentUsingAStore
's component, thecreated
hook of this component calls an async action, which will mutate the store in 1ms. - [Test 2] When mounting
MyComponentUsingAStore
's component, the vuex's state which has been populated in [Test 1] is used. So, the state fails.
As a workaround to this, we can :
- Call a
resetState()
function before each test. - Use Jest's
--runInBand
CLI parameter
However, it's far from an ideal solution as we lose test parallelization.
A solution would be export a createStore
function instead of the store instance directly (as vuex
documentation does). It would allows the user to create a new instance of vuex
/ direct-vuex
for each test.
However, this do not seems possible because of the circular dependency between the store and the modules.
Is there another way to avoid sharing an instance of vuex
?
Thanks again :)