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

280
Visualizações
VueJS / Jest - Testing if an imported function is called from a component's method

I have a VueJS 2 component that looks something like this:

<template>
  <div>
    <button @click="onFavorite">
      Add to favorites
    </button>
  </div>
</template>

<script>
import { trackFavorite } from "@/utils/analytics";

export default {
  name: "FavoriteButton",
  methods: {
    onFavorite() {
      trackFavorite("click", "favorite");
      [ ... ]
    }
  }
}
</script>

I want to write a Jest test that checks that when onFavorite is run trackFavorite is called. Tried something like this:

import { shallowMount } from '@vue/test-utils';
import FavoriteButton from '../FavoriteButton'

describe("FavoriteButton", () => {
  let wrapper

  beforeEach(() => {
    wrapper = shallowMount(FavoriteButton)
  })

  describe('.onFavorite', () => {
    beforeEach(() => {
      wrapper.vm.trackFavorite = jest.fn()
      wrapper.vm.onFavorite()
    })

    it('calls trackFavorite', () => {
      expect(wrapper.vm.trackFavorite).toHaveBeenCalled()
    })
  })
})

But it doesn't work as trackFavorite is not replaced by the Jest mock function.

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

0

  1. Use jest.mock() at the top of the test file to mock the entire import (including its methods).
  2. require() the file within the test to access the mock.
  3. With the mock reference, verify the mocked trackFavorite method is called.
// FavoriteButton.spec.js
import { shallowMount } from '@vue/test-utils'
import FavoriteButton from '@/components/FavoriteButton.vue'

jest.mock('@/utils/analytics') 1️⃣

describe('FavoriteButton.vue', () => {
  it('calls trackFavorite on button click', async () => {
    const analytics = require('@/utils/analytics') 2️⃣
    const wrapper = shallowMount(FavoriteButton)
    await wrapper.find('button').trigger('click')
    expect(analytics.trackFavorite).toHaveBeenCalled() 3️⃣
  })
})

demo

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