Verifying with VueJS and Jest: How to test if a component's method calls an imported function

I've created a VueJS 2 component that has the following structure:

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

Now, I am attempting to write a Jest test to verify that when onFavorite is executed, trackFavorite is called. Here's a snippet of what I've tried:

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('should invoke trackFavorite', () => {
      expect(wrapper.vm.trackFavorite).toHaveBeenCalled()
    })
  })
})

However, this approach is not working as expected because trackFavorite is not being replaced by the Jest mock function.

Answer №1

  1. Start by using jest.mock() in the test file to mock the entire import, including its methods.
  2. Next, use require() within the test to access the mock.
  3. After obtaining the mock reference, ensure that the mocked trackFavorite method is being 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️⃣
  })
})

Check out the demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Different methods to obscure solely URLs in AngularJS

Is there a way to effectively obfuscate URLs in AngularJS? Currently, I am using base 64 encoding as a method of obscuring my URLs. For example, let's say my URL is: I encode and decode it like this: aHR0cDovLzE5Mi4wLjAuMC9teS91cmwv However, when ...

What is the best way to assign an ID to a specific HTML element within NetSuite's Document Object Model

Attempting to utilize jQuery in NetSuite to assign a value to an element for testing purposes, but struggling to locate the HTML DOM ID of certain custom drop-down lists. It's not the internal ID. For example: <input type="text" id="soid"> Wh ...

Preserve the wpColorPicker selection using personalized knockout bindings

Utilizing wpColorPicker and knockout, my goal is to update the color picker value in my observable and then store it in the database as JSON. While other elements successfully update and save, there seems to be an issue with my custom binding for the data ...

Can you explain the contrast between `/:foo*` and `/:foo(.*)` when used in express routes?

When using Express, it is possible to define endpoints with different paths: app.get('/:foo*', function(req, res) { ... }); app.get('/:foo(.*)', function(req, res) { ... }); Although these two paths may appear similar, what sets them ...

Troubleshooting issues with Angular's scope functionality

Here is my controller: angular.module('app', []) .controller('ctrl', ['$scope', function ($scope) { $scope.daysPerMonth = new Date(year, month).getDate(); }] ); This is the corresponding html: <div ng-app> <h1&g ...

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...

Angular: module instantiation unsuccessful

Just getting started with Angular and running into an issue where the module seems to be unavailable. https://docs.angularjs.org/error/$injector/nomod?p0=plopApp My code is very basic at the moment, just setting things up: @section scripts{ <script s ...

Jquery button click event is malfunctioning after the inclusion of jquery keyboard plugin

When I try to gather user input from a textbox using jQuery keyboard.js, the functionality works perfectly fine if I exclude the virtual keyboard code. For more information on keyboard.js, you can visit: https://github.com/Mottie/Keyboard/wiki Below is t ...

I possess 9 captivating visuals that gracefully unveil their larger counterparts upon being clicked. Curiously, this enchanting feature seems to encounter a perplexing issue within the realm of web browsing

<style type="text/javascript" src="jquery-1.11.0.min.js"></style> <style type="text/javascript" src="myCode.js"></style> </body> //jquery is within my site directory on my desktop $(document).ready(function(){ //note: $("#ar ...

AngularJS options for selecting items: radio buttons and checkboxes

I am currently working on creating a concatenated string based on the selection of radio buttons and checkboxes. There are two radio button groups and one checkbox group. One of the radio button groups is functioning correctly, but the other automatically ...

Getting the value from the object that holds the Provider/Consumer using React's Context API

Below is a demonstration using the Context API object with a library called 'react-singleton-context'. Check it out here. In my Menu.js file, I have the code snippet console.log(useSharedDataContext()). This displays an object containing Consume ...

Is it better to import and use useState and useEffect, or is it acceptable to utilize React.useState and React.useEffect instead?

When I'm implementing hooks for state, effect, context, etc, this is my usual approach: import React, { useState, useEffect, useContext } from 'react'; However, I recently discovered that the following also works perfectly fine: import Re ...

Using ReactJS to incorporate events with an external DOM element

I am using ReactJS version 16.13.1 and I have the need to display an external DOM element along with its events. Let's consider having a <button type="button" id="testBtnSiri" onclick="alert('Functionality exists');">Testbutton Sir ...

Show an alternative option in the dropdown menu

Currently working with the Select component from Material UI, and here's what I'm trying to achieve:https://codesandbox.io/s/divine-water-zh16n?file=/src/App.js Situation: With an account object like {id:1, name:'name'}, I want to sel ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Having trouble with .animate() function?

Struggling to animate the position of my background image $(function() { $('#nav1').bind('click',function(event){ $('ul.nav').stop().animate({backgroundPosition: 'right top'}, 1000); }); $(function() { ...

What is the best way to display a 404 error page for a nonexistent child page on a WordPress site?

After building our site with WordPress, I noticed that non-existent child page routes are not being redirected. For instance, let's say we have a page called about-us with the URL http://example.com/about-us. If I try to access a non-existing child p ...

Implementing OAuth2 in a Microservices architecture to establish a user account

In my current setup, I am utilizing a React Application along with a separate Express API. My goal is to allow users to register through my React app. To do this, I believe the oauth2 flows should follow these steps: Prompt the user for information (suc ...

Encountering a Javascript Error when trying to begin

As a beginner in Javascript, I am venturing into designing a simple website that incorporates Javascript. Currently, my focus is on building a calculator. However, upon loading my website, nothing seems to initiate and there are no error messages displayed ...

Error message: JavaScript JSON variable undefined in AWS Lambda

My lambda function is being triggered by an IoT rule that sends a MQTT message in JSON format. I am facing an issue where the top level fields are logging correctly, but when it comes to nested objects in the JSON, they appear as "undefined". Even after tr ...