If you’ve ever worked with Vuex in strict mode, you’ve likely come across this error:

Do not mutate vuex store state outside mutation handlers.

Since strict mode continuously does a deep watch on all of the data in all of your Vuex store modules, it’s very hard on performance, and it’s therefore disabled in production. And since your jest unit tests are oblivious to these errors, they’ll pass even if strict mode is catching this problem. As a result, it’s easy for production code to get into a state in which vuex store state is being modified outside mutations, and you only see the error when you’re developing locally in strict mode. Such was the case for me this past week, and I decided that it’d be nice to have a way to fail CI in this situation. The code below is the idea that I came up with.

import Vue from 'vue';
import Vuex from 'vuex';
// The store module we're wanting to test 
import movies from './index';

Vue.use(Vuex);

const store = new Vuex.Store({
  namespaced: true,
  modules: {
    movies
  },
  strict: true
});

describe('movies store', () => {
  test('fetching movies should not alter Vuex state outside of mutations', () => {
    let cleanConsole = true;

    jest.spyOn(console, 'error').mockImplementation(() => {
      cleanConsole = false;
    });

    return store.dispatch('movies/fetch', { username: 'martynchamberlin' }).then(() =>
      expect(cleanConsole).toEqual(true);
    );
  });
});

It’s pretty simple, really. The idea is that we use jest’s spyOn method to keep track of any console.error calls that are made during the execution of the tested code. You can use this approach on a jest test for anything—you don’t have to be testing store code. You could have this on a helper class that you fear will have a proclivity to modify the store state directly.

The beautiful thing about tests is that once you’ve got them passing and integrated into your master branch, you never have to worry about a regression for the thing they’re testing. The peace of mind that this brings makes exploring solutions like this one well worth the effort.