I'm fairly new to Vue 3 and Pinia, but I could not find an answer to my Question so far... So lets dive into my problem...
I have following Example Store:
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
const useExamplePiniaStore = defineStore('example-pinia-store', () => {
const count = ref(0)
function increment() {
count.value += 1
}
function increaseBy10() {
count.value += 10
}
function increaseBy11() {
increment()
increaseBy10()
}
return {
count,
increment,
increaseBy10,
increaseBy11
}
})
And following Test File:
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { setActivePinia } from 'pinia'
import { createTestingPinia } from '@pinia/testing'
import usePiniaStoreExample from '@/examples/ExamplePiniaStore'
describe('ExamplePiniaStore.ts', () => {
beforeEach(() => {
setActivePinia(createTestingPinia({ createSpy: vi.fn, stubActions: false }))
})
it('test increase', () => {
const store = usePiniaStoreExample()
expect(store.count).toBe(0)
expect(store.increaseBy10).toHaveBeenCalledTimes(0)
store.increaseBy10()
expect(store.count).toBe(10)
expect(store.increaseBy10).toHaveBeenCalledTimes(1)
store.increaseBy11()
expect(store.count).toBe(21)
expect(store.increaseBy10).toHaveBeenCalledTimes(2)
})
})
My Problem: I would like to test that "increaseBy10" has been called by "increaseBy11" without changeging its implementation.
The Check expect(store.count).toBe(21)
shows that the value has changed accordingly,
but toHaveBeenCalledTimes(2)
always says "AssertionError: expected "spy" to be called 2 times, but got 1 times." and I do not understand why and what I'm doing wrong.
I have tried to find other / similar Problems, but I was either to stupid to understand the Issue or the Solution was for Jest or other Testing Frameworks and I was not able to make the solutions work for me.
Any help and explaination is highly appriciated. Thank you.
Best Regards
The use of Pinia setup function instead of setup options limits the testability. increaseBy11
refers local increaseBy10
function, there's no way how it could be spied or mocked outside setup function scope.
This won't happen if actions are consistently referred as this
methods:
actions:
increaseBy10() {
this.count += 10
},
increaseBy11() {
this.increment()
this.increaseBy10()
},
...