vue.jsvuejs2vuejs3vuex

Testing Vuex reducer/mutation in Vue3/Vue-test-utils


I am in the process of migrating to Vue3, so please excuse me for not just using Pinia. I have a reducer like this:

export const mutations: MutationTree<UiState> = {
  SET_LOADING: (state, loading) => {
    Object.assign(state, loading); // before Vue3 this was Vue.set(...) for reactivity
  },
};

and a test like this

it('should set consultationLoading', () => {
  const state = uiState();
  const loading = true;
  const { SET_LOADING } = mutations;
  SET_LOADING(state, loading);
  expect(state.loading).toBe(loading);
});

Since I cannot use Vue.set() (from import Vue from 'vue';) anymore, I just went with Object.assign as recommended in another post. But the state is not updating in the test.


Solution

  • The purpose of Vue.set is to trigger an update where it won't normally work by assignment due to the limitations of Vue 2, this is no longer a problem in Vue 3.

    This is JavaScript and not reactivity problem. Currently it's Object.assign(obj, bool) which does nothing.

    Should be:

    Object.assign(state, { loading: true })
    

    Which is the same as:

    state.loading = true