Vue:如何使用 sinon spy 断言组件方法被调用

Vue: how to assert with sinon spy that component method was called

我有一个页面组件:

<template>
  ...
  <button
    id="some-button"
    @click="clicked"
  >
    Button
  </button>
  ...
</template>
...
export default {
  name: 'MyComponent',
  ...
  methods: {
    fetchRequest: async function () {
    ...
    }
    clicked: async function () {
      ...

      this.fetchRequest()
    }
    ...

还有我的测试:

it('should fetch after clicking on that specific button', async () => {
  const spyFetchRequest = sinon.spy()

  wrapper = createWrapper(MyComponent, {
    provide() { return { repository: testRepository }},
    mocks: {
      fetchRequest: spyFetchRequest,
    },
  })

  await new Promise(resolve => setTimeout(resolve, 0))

  await wrapper.get('#some-button').trigger('click')

  expect(spyFetchRequest.calledOnce).to.be.true
})

但是我得到的是 false

AssertionError: expected false to be true
+ expected - actual

-false
+true

我在这里错过了什么?

mocks 安装选项不用于模拟组件方法。这是为了模拟全局实例属性(例如,$router$store)。

要模拟组件方法,请在组件定义的 methods 上使用 sinon.spy() 以及方法名称:

import MyComponent from '@/components/MyComponent.vue'

it('should fetch after clicking on that specific button', async () => {
  const spyFetchRequest = sinon.spy(MyComponent.methods, 'fetchRequest')

  const wrapper = shallowMount(MyComponent)

  ...

  expect(spyFetchRequest.calledOnce).to.be.true
})

demo