3

Using vue-test-utils to test the component using pinia, I need to modify the value of the state stored in pinia, but I have tried many methods to no avail. The original component and store files are as follows.

// HelloWorld.vue
<template>
    <h1>{{ title }}</h1>
</template>

<script>
import { useTestStore } from "@/stores/test";
import { mapState } from "pinia";

export default {
    name: "HelloWorld",
    
    computed: {
        ...mapState(useTestStore, ["title"]),
    },
};
</script>
// @/stores/test.js
import { defineStore } from "pinia";

export const useTestStore = defineStore("test", {
    state: () => {
        return { title: "hhhhh" };
    },
});

The following methods have been tried.

  1. Import the store used within the component to the test code and make changes directly, but the changes cannot affect the component.
// test.spec.js
import { mount } from "@vue/test-utils";
import { createTestingPinia } from "@pinia/testing";
import HelloWorld from "@/components/HelloWorld.vue";
import { useTestStore } from "@/stores/test";

test("pinia in component test", () => {
 const wrapper = mount(HelloWorld, {
     global: {
         plugins: [createTestingPinia()],
     },
 });
 const store = useTestStore();
 store.title = "xxxxx";

 console.log(wrapper.text()) //"hhhhh";
});
  1. Using the initialState in an attempt to overwrite the contents of the original store, but again without any effect.
// test.spec.js
import { mount } from "@vue/test-utils";
import { createTestingPinia } from "@pinia/testing";
import HelloWorld from "@/components/HelloWorld.vue";

test("pinia in component test", () => {
 const wrapper = mount(HelloWorld, {
     global: {
         plugins: [createTestingPinia({ initialState: { title: "xxxxx" } })],
     },
 });
 console.log(wrapper.text()) //"hhhhh";
});
  1. Modify the TestingPinia object passed to global.plugins in the test code, but again has no effect.
// test.spec.js
import { mount } from "@vue/test-utils";
import { createTestingPinia } from "@pinia/testing";
import HelloWorld from "@/components/HelloWorld.vue";

test("pinia in component test", () => {
 const pinia = createTestingPinia();
 pinia.state.value.title = "xxxxx";
 const wrapper = mount(HelloWorld, {
     global: {
         plugins: [pinia],
     },
 });
 console.log(wrapper.text()) //"hhhhh";
});
  1. Use global.mocks to mock the states used in the component, but this only works for the states passed in with setup() in the component, while the ones passed in with mapState() have no effect.
// test.spec.js
import { mount } from "@vue/test-utils";
import { createTestingPinia } from "@pinia/testing";
import HelloWorld from "@/components/HelloWorld.vue";

test("pinia in component test", () => {
 const wrapper = mount(HelloWorld, {
     global: {
         plugins: [createTestingPinia()],
         mocks: { title: "xxxxx" },
     },
 });
 console.log(wrapper.text()) //"hhhhh"
});
Red Panda
  • 41
  • 1
  • 3

4 Answers4

1

This has been resolved using jest.mock().

import { mount } from "@vue/test-utils";
import { createPinia } from "pinia";
import HelloWorld from "@/components/HelloWorld.vue";

jest.mock("@/stores/test", () => {
    const { defineStore } = require("pinia");
    const useTestStore = defineStore("test", { state: () => ({ title: "xxxxx" }) });
    return { useTestStore };
});

test("pinia in component test", () => {
    const wrapper = mount(HelloWorld, {
        global: { plugins: [createPinia()] },
    });
    expect(wrapper.text()).toBe("xxxxx");
});
Red Panda
  • 41
  • 1
  • 3
0

Thanks to Red Panda for this topic. I use "testing-library", and "vue-testing-library" instead of "vue-test-utils" and "jest", but the problem is the same - couldn't change pinia initial data of the store. I finally found a solution for this issue without mocking the function. When you $patch data, you just need to await for it. Somehow it helps. My code looks like this and it totally works:

Popup.test.js

import { render, screen } from '@testing-library/vue'
import { createTestingPinia } from '@pinia/testing'
import { popup } from '@/store1/popup/index'
import Popup from '../../components/Popup/index.vue'

describe('Popup component', () => {
  test('displays popup with group component', async () => {
    render(Popup, {
      global: { plugins: [createTestingPinia()] }
    })
    const store = popup()
    await store.$patch({ popupData: 'new name' })
    screen.debug()
  })
})

OR you can set initialState using this scheme:

import { render, screen } from '@testing-library/vue'
import { createTestingPinia } from '@pinia/testing'
import { popup } from '@/store1/popup/index'
import Popup from '../../components/Popup/index.vue'

  test('displays popup with no inner component', async () => {
    const { getByTestId } = render(Popup, {
      global: {
        plugins: [
          createTestingPinia({
            initialState: {
              popup: {
                popupData: 'new name'
              }
            }
          })
        ]
      }
    })
    const store = popup()
    screen.debug()
  })

Where popup in initialState - is the imported pinia store from @/store1/popup. You can specify any of them there the same way.

Popup.vue

<script>
import { defineAsyncComponent, markRaw } from 'vue'
import { mapState, mapActions } from 'pinia'
import { popup } from '@/store1/popup/index'

export default {
  data () {
    return {}
  },
  computed: {
    ...mapState(popup, ['popupData'])
  },
....

enter image description here

dean0071
  • 26
  • 3
0

I'm working on a project using Vue 3 with composition API styling.

Composition API is used for both components and defining my store.

Here is my store

player.js

import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export const usePlayerStore = defineStore('player',()=>{
    const isMainBtnGameClicked = ref(false)

    return { isMainBtnGameClicked }
})

MyComponent.vue

//import { usePlayerStore } from '...'
const playerStore = usePlayerStore()        
playerStore.isMainBtnGameClicked = true

isMainBtnGameClicked from my store is updated properly.

You can also update variables from components by passing them by reference to the pinia store. It's working in my project.

ufa9
  • 29
  • 7
0

For sake of saving future me many hours of trouble, there is a non-obvious thing in play here - the event loop. Vue reactivity relies on the event loop running to trigger the cascade of state changes.

When you mount/shallowMount/render a component with vue-test-utils, there is no event loop running automatically. You have to trigger it manually for the reactivity to fire, e.g.

await component.vm.$nextTick;

If you don't want to mess around with ticks, you have to mock the store state/getters/etc. (which the docs strongly lean toward, without explaining the necessity). Here OP mocked the whole store.

See also: Vue-test-utils: using $nextTick multiple times in a single test

nerdstrike
  • 181
  • 2
  • 4