Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!