vuex icon indicating copy to clipboard operation
vuex copied to clipboard

Errorenous state error during async testing

Open tylfin opened this issue 3 years ago • 4 comments

Version

4.0.2

Steps to reproduce

For whatever reason, we're only able to reproduce this error in a Docker container, but our test suite raises this error:

Error: [vuex] do not mutate vuex store state outside mutation handlers.

Following the traceback, it points to an async action in an HTTP module:

const mutations = {
  [types.SET_GETTING_METRICS_STATUS](state, flag) {
    state.gettingMetricsStatus = flag;
  },
  [OMITTED]
}

const module = (HTTP) => ({
  state: defaultState,
  mutations,
  actions: {
    async getStatus({ commit }) {
      try {
        commit(types.SET_GETTING_METRICS_STATUS, true);
       [OMITTED]

Complaining that the SET_GETTING_METRICS_STATUS mutation is attempting to mutate state outside of mutation handlers.

Our test case is fairly simple as well, e.g.:

it("should update state correctly", async () => {
    const store = createStore(status.module(HTTP));

    const stub = sinon.stub(HTTP, "get");
    stub.onCall(0).returns({
    data: {
        [OMITTED]
    });

    expect(store.state).to.deep.equal(defaultState);

    await store.dispatch("getStatus");
    [OMITTED]

What is expected?

The test case should finish without error.

What is actually happening?

Vuex is incorrectly stating that the mutation is attempting to mutate state outside of a mutation.

tylfin avatar Feb 22 '22 15:02 tylfin

Seeing this too happen in one of our test using Cypress component testing

Akryum avatar May 04 '22 12:05 Akryum

It seems to happen if there is another store created somewhere in the code (although not used in the app).

Akryum avatar May 04 '22 13:05 Akryum

@Akryum Ah sorry I should've updated this issue, but that's exactly what I found too. We had a store being created by default outside of any function in App.js, and a mock-store being created by our test.

I tried to trace through the Vue/Vuex code, but couldn't find the culprit given it's designed around creating multiple stores. We ended up making our global store creation lazy and only initialized when the actual app is started 🤷

If someone has time to look, I would first investigate the possibility of namespace collisions

tylfin avatar May 05 '22 13:05 tylfin

For me it helped to make a deep clone on the mock store configuration like described in the Vuex docs: https://v1.test-utils.vuejs.org/guides/using-with-vuex.html#testing-a-running-store

import { cloneDeep } from 'lodash'

test('increments "count" value when "increment" is committed', () => {
  const localVue = createLocalVue()
  localVue.use(Vuex)
  const store = new Vuex.Store(cloneDeep(storeConfig))
  expect(store.state.count).toBe(0)
  store.commit('increment')
  expect(store.state.count).toBe(1)
})

lisilinhart avatar Oct 03 '22 14:10 lisilinhart