vuex-mock-store
Simple and straightforward mock for Vuex v3.x Store
Supports using mapMutations
and mapActions
as well as directly doing this.$store.commit()
and this.$store.dispatch()
Installation
npm install -D vuex-mock-store
yarn add -D vuex-mock-store
Usage
ℹ️: All examples use Jest API
Usage with vue-test-utils:
import { Store } from 'vuex-mock-store'
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
const store = new Store()
const mocks = {
$store: store,
}
afterEach(() => store.reset())
describe('MyComponent.vue', () => {
let wrapper
beforeEach(() => {
wrapper = mount(MyComponent, { mocks })
})
it('commits init on creation', () => {
expect(store.commit).toHaveBeenCalledOnce()
expect(store.commit).toHaveBeenCalledWith('init')
})
it('dispatch save when clicking button', () => {
wrapper.find('button.save').trigger('click')
expect(store.dispatch).toHaveBeenCalledOnce()
expect(store.dispatch).toHaveBeenCalledWith('save', { name: 'Eduardo' })
})
})
Initial state and getters
You can provide a getters
, and state
object to mock them:
const store = new Store({
getters: {
name: 'Eduardo',
},
state: {
counter: 0,
},
})
Modules
To mock modules state
, simply provide a nested object for state
:
new Store({
state: {
moduleA: {
moduleC: {
value: 'foo',
},
},
moduleB: {
value: 'bar',
},
},
})
Testing actions and mutations depend whether your modules are namespaced or not. If they are namespaced, make sure to provide the full action/mutation name:
expect(store.commit).toHaveBeenCalledWith('moduleA/setValue')
expect(store.dispatch).toHaveBeenCalledWith('moduleA/postValue')
expect(store.commit).toHaveBeenCalledWith('setValue')
expect(store.dispatch).toHaveBeenCalledWith('postValue')
Mutating state
, providing custom getters
You can modify the state
and getters
directly for any test. Calling store.reset()
will reset them to the initial values provided.
API
Store
class
constructor(options)
options
state
: initial state object, default: {}
getters
: getters object, default: {}
state
Store state. You can directly modify it to change state:
store.state.name = 'Jeff'
getters
Store getters. You can directly modify it to change a value:
store.getters.upperCaseName = 'JEFF'
reset
Reset commit
and dispatch
spies and restore getters
and state
to their initial values
commit
& dispatch
Spies. Dependent on the testing framework
Related
License
MIT