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



我有一个单独的页面组件:

<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
})

演示

最新更新