vuex-mock-context
v1.2.0
Published
Test mock for vuex context
Downloads
870
Readme
vuex-mock-context
Test mock for vuex context
Install
npm install vuex-mock-context -D
Why
For testing that vuex actions commit mutations and dispatch actions as expected.
See Composing Actions in the Vuex docs.
Usage
You have this vuex action
save(context, payload) {
context.commit('INCREMENT_SAVE_COUNT');
return context.dispatch('update', payload);
}
You can test it like this
import {create} from 'vuex-mock-context';
import actions from './actions';
test('save action increments count and then updates', function() {
// set up mock context
const context = create();
// invoke action handler
return actions.save(context, {value: 'whatever'})
.then(() => {
// verify context interactions
assert.deepEquals(context.log, [
{mutation: ['INCREMENT_SAVE_COUNT']},
{action: ['update', {value: 'whatever'}]}
]);
});
});
Snapshot testing
If you are using Jest or some other framework that supports snapshot testing, capture and verify context.log
with a snapshot:
expect(context.log).toMatchSnapshot();
API
import {create} from 'vuex-mock-context';
const mockContext = create(actionHandler)
Create a mock context.
actionHandler
is an optional function that receives all parameters sent to dispatch()
and returns a Promise
which will be the return value of dispatch()
. Defaults to function that returns a resolved Promise
with undefined value.
mockContext.commit()
Just like context.commit()
in vuex.
mockContext.dispatch()
Just like context.dispatch()
in vuex.
Return value is determined by actionHandler
, see above.
mockContext.log
Array of objects that represent context interactions. There are two types of interactions:
1. mutation
{mutation: [<args passed to commit>]}
For example
context.commit('DO_SOMETHING', {value: 1});
becomes
{mutation: ['DO_SOMETHING', {value: 1}]}
2. action
{action: [<args passed to dispatch>]}
For example
context.dispatch('save', {id: 5});
becomes
{action: ['save', {id: 5}]}
mockContext.state
mockContext.getters
mockContext.rootState
mockContext.rootGetters
All of these start off as an empty object. You can add properties as needed.
License
MIT