Patterns for testing Vue 3 & Pinia with <script setup> #27368
-
I expect this following test to pass, however: Navigation.cy.js: import { createTestingPinia } from "@pinia/testing";
import { useNavStore } from "@/stores/navigation";
import Navigation from ".@/components/Navigation.vue";
describe("<Navigation />", () => {
let store;
beforeEach(() => {
Cypress.config("defaultCommandTimeout", 500);
const spy = cy.spy();
createTestingPinia({
createSpy: () => spy,
});
// one way:
store = useNavStore();
// another way with the same error:
store = useNavStore(createTestingPinia({
createSpy: () => spy,
}));
cy.mount(Navigation, {
global: {
plugins: [store],
},
});
});
it("updates the navStore when the Next link is clicked", () => {
// PASSING TEST
expect(store.noteType).to.equal("inbox");
cy.contains("Next").click()
// store.setNoteType("next"); * this does not make the test pass
// store.noteType = "next" ** this does make the test pass
// ASSERTION ERROR
// expected 'inbox' to equal 'next'
expect(store.noteType).to.equal("next");
});
}); Here is the component under test Navigation.vue: <template>
<nav>
<ul>
<li @click="navStore.setNoteType('inbox')">Inbox</li>
<li @click="navStore.setNoteType('next')">Next</li>
</ul>
</nav>
</template>
<script setup>
import { useNavStore } from '@/stores/navigation';
const navStore = useNavStore();
</script> and the store navigation.js: import { defineStore } from "pinia";
export const useNavStore = defineStore("navigation", {
state: () => ({
noteType: 'inbox',
}),
actions: {
setNoteType(type) {
this.noteType = type;
},
},
}); I've manually tested this code and it works as expected, so my failing test is not set up properly. Please show me the proper pattern to test this. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
I wrote a small article about this: https://cypress-testing-handbook.netlify.app/pinia.html I have not using the "testingPinia" - I just use a real store and create a fresh one for each test. Take a look at that -- let me know what you think? |
Beta Was this translation helpful? Give feedback.
-
We use the beforeEach and cy.window to get access to the store.
You then have access to the store, getters and setters inside a test
|
Beta Was this translation helpful? Give feedback.
-
Closing this as it appears that the answer was provided by @lmiller1990 |
Beta Was this translation helpful? Give feedback.
I wrote a small article about this: https://cypress-testing-handbook.netlify.app/pinia.html
I have not using the "testingPinia" - I just use a real store and create a fresh one for each test. Take a look at that -- let me know what you think?