最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

vue.js - vue 3 pinia testing - spying and asserting on actions - Stack Overflow

programmeradmin0浏览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?

发布评论

评论列表(0)

  1. 暂无评论