Search code examples
vue.jsunit-testingvuejs3vuexpinia

I'm switching from Vuex to Pinia in Vue 3 and my unit tests are now failing. I can't seem to be able to create custom mock actions


Here's a simple example on the forgot password reset page of my app, I would want to bypass the server side and just have the password reset to succeed on click so I would write a test and use the custom test store like so:

const customStore = {
  state() {
    return {
      Authentication: {
        passwordResetSuccess: false,
      },
    };
  },
  mutations: {
    SET_RESET_PASSWORD_SUCCESS(state) {
      state.Authentication.passwordResetSuccess = true;
    },
  },
  actions: {
    forgotPasswordResetPassword() {
      this.commit('SET_RESET_PASSWORD_SUCCESS');
    },
  },
};

Then I could include the custom store in my beforeEach() and it worked great. I've tried everything I can think of to get this to work with pinia, but it doesn't seem to work.

I'm using jest along with vue/test-utils.

I basically tried just creating the test pinia store, but I can't figure out how to get the component to use the custom test store.

const useCustomStore = defineStore('AuthenticationStore', {
  state: () => ({
    passwordResetSuccess: false,
  }),
  actions: {
    forgotPasswordResetPassword() {
      this.passwordResetSuccess = true;
    },
  },
});


const authenticationStore = useCustomStore();

I can't directly add it as a plugin because it can't find an active instance of pinia.

I went through this guide: https://pinia.vuejs.org/cookbook/testing.html#unit-testing-a-store

and I also tried using jest mock as described here: https://stackoverflow.com/a/71407557/4697639

But it still failed.

If anyone has any idea how to create a custom store that can be used by the component and actually hits the custom actions, I could really use some help figuring this out. Thank you!!


Solution

  • Tao mentioned in the comments that this isn't a good way to do unit tests. I will mark this as resolved and fix how I do the testing.