0

I have the following simplified pinia store:

export const useMyStore = defineStore('myStore', () => {
  const doSomething = (param) => {
    console.log('doSomething called with: ', param)
    setData(param)
  }

  const setData = (data) => {
    console.log('setData called with: ', data)
  }

  return {
    doSomething, setData
  }
})

In my test file (vitest), I invoke doSomething(), which in turn will call setData(). I want to assert that setData() was indeed called.

describe('myStore', () => {
  test('doSomething()', () => {
    const pinia = createPinia()
    setActivePinia(pinia)
    const store = useMyStore()
    const spy = vi.spyOn(store, 'setData')

    const data = {
      name: 'doge'
    }

    store.doSomething(data)
    expect(spy).toHaveBeenCalledOnce()
  })
})

However, the above does not work. I can see the console.log messages in the output, but the assertion fails: AssertionError: expected "wrappedAction" to be called once, but got 0 times

I have also tried mocking, but it does not work either.

    const mock = vi.fn()
    store.setData = mock
    store.doSomething(data)
    expect(mock).toHaveBeenCalledOnce()

Is there a way to simply assert that setData() was called?

1
  • There is no way how this could be done in JS, you're referring setData that is local to store factory function. Use store options and "this" if you need to spy or mock actions that are called internally Commented Mar 3 at 10:54

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.