Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

282
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda