【问题标题】:Vue: how to assert with sinon spy that component method was calledVue:如何用 sinon spy 断言组件方法被调用
【发布时间】:2021-11-16 04:01:24
【问题描述】:

我有一个单页组件:

<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

我在这里错过了什么?

【问题讨论】:

    标签: vue.js sinon spy sinon-chai


    【解决方案1】:

    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

    【讨论】:

    • @MattSom 修复了演示链接。在创建包装器之前 执行此操作。包装器将使用 mocked/spied 方法作为您的点击处理程序。
    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2017-09-24
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多