N
Nuxt3mo ago
dwol

How to spy on store functions during Pinia store test?

Trying to test a Pinia store and assert the function being tested is calling other functions. Example store:
export const useTestStore = defineStore('test-store', () => {
function test1 () {
console.log('before')
test2()
console.log('after')
}

function test2 () {
console.log('test 2 called')
}

return {
test1,
test2
}
})
export const useTestStore = defineStore('test-store', () => {
function test1 () {
console.log('before')
test2()
console.log('after')
}

function test2 () {
console.log('test 2 called')
}

return {
test1,
test2
}
})
Example test:
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'

describe('useTestStore', () => {
beforeEach(() => {
const pinia = createPinia()
setActivePinia(pinia)
})

it('should call test2', () => {
const testStore = useTestStore()
const test2Spy = vi.spyOn(testStore, 'test2')
testStore.test1()
expect(test2Spy).toHaveBeenCalledOnce()
})
})
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import { setActivePinia, createPinia } from 'pinia'

describe('useTestStore', () => {
beforeEach(() => {
const pinia = createPinia()
setActivePinia(pinia)
})

it('should call test2', () => {
const testStore = useTestStore()
const test2Spy = vi.spyOn(testStore, 'test2')
testStore.test1()
expect(test2Spy).toHaveBeenCalledOnce()
})
})
But this fails with AssertionError: expected "spy" to be called once, but got 0 times. Is this possible to accomplish?
1 Reply
dwol
dwolOP3mo ago
bump
Want results from more Discord servers?
Add your server