Issue with Jest Test Trigger Event Not Invoking Method

Currently, I am in the process of writing tests for my Vue application. One particular test involves a button that triggers a logout function. The goal is to determine if the function is executed when the button is clicked.

Initially, I attempted to mock the function using jest.fn() but encountered difficulties getting it to work as expected. Another approach I tried was directly triggering the method and adding a console.log statement within the method. However, the log did not display. What could be causing this issue?

Below is my setup for the wrapper:

let wrapper;

beforeEach(() => {
    Vue.use(Vuetify);
    Vue.prototype.$router = new VueRouter();
    wrapper = shallowMount(Navigation);
});

afterEach(() => {
    wrapper.destroy();
});

it('should call logout function on button click', function() {
        let submitLogoutMock = jest.fn();
        wrapper.vm.submitLogout = submitLogoutMock;

        wrapper
            .find('#logout-button')
            .trigger('click');

        expect(submitLogoutMock).toHaveBeenCalled();
    });

The expectation is that the mocked method should be called, however, an error message stating:

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

Expected mock function to have been called, but it was not called.

Answer №1

When utilizing shallowMount, it's important to stub the methods of the component. This can be achieved either during the creation of the wrapper or by using setMethods().

All you have to do is modify your unit test:

  it('should trigger logout function when button is clicked', () => {
    const simulateLogout = jest.fn();
    wrapper.setMethods({ logout: simulateLogout });

    wrapper.find('#logout-button').trigger('click');

    expect(simulateLogout).toHaveBeenCalled();
  });

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

The constructor for audio in Next JS cannot be found

I'm facing an issue and struggling to find a solution. My project follows the standard structure of Next JS. In the root directory, I have included a components folder. Within the components folder, there is a component with the following code: imp ...

Is there a way to update an angular.js service object without using extend or copy?

I am working with 2 services and need to update a variable in the first service from the second service. Within a controller, I am assigning a scope variable to the getter of the first service. The issue I am facing is that the view connected to the cont ...

Retrieve the current state within a redux action

Many experts recommend consolidating the logic in action creators to streamline the reducer's logic. Picture a basic (normalized) state: const initialState = { parent: { allIds: [0], byId: { 0: { parentProperty: `I'm the ...

Storing user data on the client side of a website is most effectively accomplished by

I am looking to incorporate the following features: I would like to personalize the user experience by greeting them with their login name on the webpage (e.g. 'Hello, Fred!'). I also want to display or hide certain content based on the user&apo ...

What is the best way to dynamically retrieve a URL and utilize it as a hyperlink using jQuery?

Is there a way to retrieve the current URL and use it as a link in jQuery? For example, if my browser is currently on page mysite.com/index.php?page=post&see=11, I would like to use this URL in my link and append /new/ after the domain name, like so: ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...

"Implementing ASP.NET MVC4 with Razor: Dynamically filtering a dropdown list based on the selected value from another dropdown

Currently, I am facing a challenge where I need to filter the options of a dropdown list based on the value selected from another dropdown. Within my database, there are tables containing all countries and all cities in the world, with a foreign key linkin ...

Uncover the hidden message in a string encoded for JavaScript

This encoded HTML code is intended for use in a JavaScript function <div class=\"ProductDetail\"><div style=\"width:780px\">\r\n\t<div class=\"baslik\" style=\"margin: 0px; padding: 5px 10px ...

Possibility for using navigator.GetUserMedia in Internet Explorer

How can I access a webcam through JavaScript/jQuery? I have successfully opened the webcam in Chrome and Mozilla, but the navigator.GetUserMedia feature does not work in Internet Explorer. Is there a way to achieve this with JavaScript or jQuery in IE? ...

Need assistance with debugging the current solution for the todo App using Commander or considering a different approach with Readline and Event Emitter?

I'm currently working on developing a CLI for a Node.js exclusive todo application using the commander and conf modules within Node.js, along with chalk to add color to the output. I've encountered some issues that I'm unsure how to resolve: ...

Exploring the capabilities of utilizing filters within a ternary operator in AngularJS

Can a filter be applied to a variable in the template within a ternary operation? <img ng-src="{{ image_url && image_url|filter:"foo" || other_url }}"> In this scenario, the filter is custom-made and I prefer not to alter it to accommodate ...

Issue: React cannot render Objects as children (received: [object Promise]). If you intended to display multiple children, please use an array instead. (Next)

My dilemma is this: I am trying to display my GitHub repositories on a React component, but I keep encountering the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, u ...

What are some ways to rejuvenate a computed property?

Is there a way to refresh the data displayed in someData after it has been updated and saved on the server? I have tried using $recomputed('someData'), but it's not working as expected. I believe I might need to utilize a Promise, but I&apo ...

Adding several lines of HTML content from an object using jQuery's append method

Currently, this is what I have: $(document).ready(function() { $.ajax({ type:"GET" , url:'{{url("/api/getcart")}}' , dataType:"json", success: function(data){ $('#price').append(data.cartitems[1].product.pr ...

What steps can I take to modify my webpage, like a dashboard, on the internet?

Whenever I click on a menu item in the sidebar of my HTML file, I want only the body section to change without affecting the navigation or sidebar content. For instance, if I select the "Coding Convention" menu in the sidebar, I would like the page to swi ...

After utilizing Geolocation, the input fields in Ionic/Angular JS are failing to update accurately

Currently, I am in the process of developing a new App using Ionic and Angular JS. Specifically, in one of the app tabs, I am utilizing geolocation to populate four fields (street name, street number, latitude, and longitude). Below is the snippet of my c ...

Tips for extracting parameters from a URL using Express JS in a custom manner

Recently, I set up a server using the express package and encountered an issue while trying to extract parameters from the URL in a specific format. The URL structure is as follows: (notice there's no '?' indicating parameters). I am lookin ...

Divide a string into smaller sections beginning at " ] " and concluding with "As"

In Microsoft SQL Server 2008 R2, I have fetched a string from a stored procedure using the query: EXEC sp_helptext 'MyStoredProcedureName';. My task is to divide this string into arrays or substrings that start from the closing parenthesis "]" a ...