How to get basic test for component with Pinia working? #1540
-
Hi 👋, Sorry, but I'm a newbie and might be missing something super trivial. I am trying to follow this guide: https://pinia.vuejs.org/cookbook/testing.html#unit-testing-components To get the following test working: import { describe, it, expect } from 'vitest'
import { createTestingPinia } from '@pinia/testing'
import { mount } from '@vue/test-utils'
import { storeToRefs } from 'pinia'
import Create from '@/components/greeting/Create.vue'
import { useGreetingStore } from '@/stores/greeting.js'
describe('Create', () => {
it('renders properly', async () => {
const arbitraryMessage = 'arbitrary test greeting'
const wrapper = mount(Create, {
global: {
plugins: [
createTestingPinia({
initialState: {
greeting: {
greetings: [
{
message: arbitraryMessage,
}
],
},
},
}),
],
},
})
const store = useGreetingStore()
wrapper.find('input').setValue('arbitrary message')
await wrapper.find('input[type=submit]').trigger('click')
// I'm trying to check if a new greeting was added, but nothing has worked
// these are some things I've tried:
//const { greeting } = storeToRefs(store)
//console.log(greeting)
})
}) Thank you for any pointers and guidance you can provide. This is my component: <script setup>
import { ref } from 'vue'
import { useGreetingStore } from '@/stores/greeting'
const store = useGreetingStore()
const greeting = ref({
message: '',
})
function processForm() {
console.log("called")
store.addGreeting(greeting)
greeting.value['message'] = ''
}
</script>
<template>
<h2>Create a Greeting:</h2>
<form @submit.prevent="processForm">
<input v-model="greeting['message']">
<input type="submit" value="Save" />
</form>
</template> This is my store: import { defineStore } from 'pinia'
export const useGreetingStore = defineStore(
'greeting',
{
state: () => {
return {
greetings: [
{
id: 1,
message: 'hello, world'
},
{
id: 2,
message: 'bye, world'
},
],
}
},
actions: {
addGreeting(greeting) {
this.greetings.push({
message: greeting.value['message'],
})
},
deleteGreeting(deletedGreeting) {
const index = this.greetings.findIndex(
(greeting) => greeting['id'] === deletedGreeting["id"]
);
const noGreetingWithId = -1;
if (index != noGreetingWithId) this.greetings.splice(index, 1);
},
},
},
) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I was able to make more progress after finding this thread: #828 But the This test:
Yields an unmodified state:
I'm pretty sure I'm missing something trivial, but I can not figure it out. Thanks again for your time and sorry for my lack of understanding 🙏 |
Beta Was this translation helpful? Give feedback.
-
ok, I don't know why I couldn't get the below to work before. But everything seems to work now.
Sorry for all of the churn 😔 |
Beta Was this translation helpful? Give feedback.
ok, I don't know why I couldn't get the below to work before. But everything seems to work now.