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

Time:09-24

I have a singe page component:

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

      this.fetchRequest()
    }
    ...

And my test:

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

However I get false instead:

AssertionError: expected false to be true
  expected - actual

-false
 true

What am I missing here?

CodePudding user response:

The mocks mounting option is not intended to mock component methods. That's for mocking global instance properties (e.g., $router or $store).

To mock a component method, use sinon.spy() on the component definition's methods along with the method's name:

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

const spyFetchRequest = sinon.spy(MyComponent.methods, 'fetchRequest')

demo

  • Related