Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
Mocking methods with jest and vue

I have been trying to test if a method is called in a Vue component when a specific button is triggered.

I've been successfull using this method at first:

it('should call the methodName when button is triggered', () => {
  const methodNameSpy = jest.spyOn(wrapper.vm, 'methodName')

  wrapper.find('.is-success').trigger('click')

  expect(methodNameSpy).toBeCalled()
})

So this worked just fine for some components, but I still get an error telling me that it did not get called on some other components

Error: expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

I have one idea on why this simple test is failling in this case, but i have no idea on how to fix it or even if it is the reason.

This component is a "tooltip", once the save / close button is pressed, it closes, and disapears. Maybe that's why the test is failing, because it can't find the tested elements anymore.

Here is the component and the tests

component.vue

<template lang="html">
    <div class="editresewin" @click.stop>
        <div class="topbar">
            <button
                class="button is-danger"
                @click="close"
            >
                <b-icon icon="close" />
            </button>
            <button
                class="button is-success"
                @click="save"
            />
            <h2 class="...">Title</h2>
        </div>
        <div class="...">
            <div class="...">
                <label>Label</label>
                <input .../>
            </div>
        </div>
    </div>
</template>

component.spec.vue

describe('TheEditResourceFile', () => {
  let wrapper
  let defaultParams

  beforeEach(() => {
    defaultParams = {
      localVue,
      i18n,
      router,
      store,
      propsData: {
        args: {
          title: '',
          description: '',
        },
        type: 'file',
      },
    }
    wrapper = shallowMount(TheEditResourceFile, defaultParams)
  })

  it('should trigger the save method', () => {
      const saveSpy = jest.spyOn(wrapper.vm, 'save')

      wrapper.find('.is-success').trigger('click')

      expect(saveSpy ).toBeCalled()
    })
})

Let me know if more clafication is needed.

Thank you for your help.

Edit: Wrong code on failed test.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. In Vue 2, the mock/spy on the component method must be done on the component's .methods definition -- not the wrapper -- before mounting. (As of Vue 3.2.31, this order is no longer required for methods called post-mount.)

  2. The trigger('click') call needs to be awaited because it invokes the bound method asynchronously.

  3. The spy is always truthy, so toBeTruthy() is a meaningless assertion. Instead, assert toHaveBeenCalled() on the spy.

it('should trigger the save method', () => {
  1️⃣
  const saveSpy = jest.spyOn(TheEditResourceFile.methods, 'save')
  wrapper = shallowMount(TheEditResourceFile, defaultParams)

  2️⃣
  await wrapper.find('.is-success').trigger('click')

  3️⃣
  expect(saveSpy).toHaveBeenCalled()
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda