[Vuejs]-Test if mutation triggered reactivity

0👍

Mutations are quite simple to test because they are just functions that rely entirely on their arguments. A trick is this: If you are using ES2015 modules and put your mutations inside your store.js file, you must export mutations as a named export, in addition to the default export.

Then to verify certain triggers are fired you could use the spies of Sinon.

const state = { ... }

// export `mutations` as a named export
export const mutations = { ... }

export default new Vuex.Store({
  state,
  mutations
})

Sample test using Mocha and Chai (you could use other libraries too):

// mutations.js
export const mutations = {
  triggerMutation: state => state.doSth
}

And the spec file:

// mutations.spec.js
var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinon-chai');
var mutations = require('store');
var expect = chai.expect;
chai.use(sinonChai);

const { mutate } = mutations

describe('mutations', () => {
  it('Mutate should trigger', () => {
    // set up your spy
    var spy = sinon.spy();

    // apply the mutation
    mutate(spy);

    // assert result
    expect(spy).to.have.been.calledWith('triggerMutation');
  })
})
👤Rafet

Leave a comment