Here's a method to verify a function prop was invoked using react-testing-library

There are 3 key files:

First File: utilities.js

export const utilities = () => ({
  func: () => 'Function was executed',
});

Second File: AppComponent.js

import React from 'react';
import { utilities } from './utilities';

const AppComponent = () => {
  const { func } = utilities();
  return (
    <><button onClick={func}/></>
  );
};

export default AppComponent;

Third File: AppComponent.test.js

import React from 'react';
import userEvent from '@testing-library/user-event';
import { screen, render } from '@testing-library/react';
import AppComponent from './AppComponent';
import { utilities } from './utilities';

jest.mock('./utilities', () => ({
  utilities: jest.fn(),
}));

test('function is called', () => {
  utilities.mockImplementation(() => ({
    func: jest.fn(),
  }));

  render(
    <AppComponent />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(???????).toHaveBeenCalled();
});

This line holds the answer:

expect(???????).toHaveBeenCalled();

The query: How do I verify if the func function was invoked? I attempted using something like expect(utilities().func) but it didn't work as expected.

Answer №1

Store the function in a variable and apply it in expect assertion

test('checking if bar is invoked', () => {
  const bar = jest.fn()
  utilities.mockImplementation(() => ({bar}));

  render(
    <ComponentUnderTest />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(bar).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

Guide on storing a promise response in an external object in VUE

I am currently working on integrating the higchart network graph in vue. Everything seems to be functioning properly with static data. However, when I attempt to retrieve data using axios, it fails to work. export default { data() { return { ne ...

Tips for setting up Code Coverage in a Cypress environment for testing a NextJS build simultaneously

We are currently exploring the possibility of integrating code coverage into our setup utilizing cypress and nextjs. Within our cypress configuration, we utilize the next() function to mimic backend requests within nextjs. The cypress.config.ts file is st ...

Creating a custom type for accepted arguments in a Typescript method

Below is the structure of a method I have: const a = function (...args: any[]) { console.log(args); } In this function, the type of args is any[]. I am looking to create a specific type for the array of arguments accepted by this method in Typescript. ...

Unexpected issue: Ajax sending empty values to populate SQL table using POST method

Attempting to input data from form fields into an SQL table using Ajax, encountering a problem. The Ajax request seems to be functioning correctly, but it is not capturing the values of the inputs before inserting a new row into the SQL table. The new row ...

Update each number in an array by appending a string within a table in an Angular component, rather than the

I have created a function that decides on a comment based on the result number added to an array and displays it in a table. However, calling this function within the template is causing a performance slowdown. Is there a way to achieve the same outcome w ...

Retrieving data from an external API using Express.js and displaying it on a website

I'm facing a challenge in handling a solution with node.js and express.js utilizing pug for rendering HTML. I need to render on a single page by retrieving values from separate HTTP GET requests from different websites. My goal is for express/node to ...

HTML and JavaScript are not communicating properly

Need help with creating a slideshow using JavaScript. The code works on JSFiddle, but not in my local environment. Can someone point out where I might be going wrong? HTML5 <!DOCTYPE html> <html> <head> <title>slider</titl ...

What is the best way to update a Bootstrap Toggle with a dynamic value?

When performing an update action, the user can click on an element in a table and change the value by toggling a bootstrap toggle. However, I am unsure of how and where to apply this change. Here is the code snippet: Initially, the user clicks on the ele ...

What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information. { "results": [ { "address_components": [ ...

What is the proper way to invoke a function that is part of a child component as a property in a React application?

In my app.js file, I have included a unique component called "SigningComponent" with the following code: onSign = () => { this.setState({ route: "home" }); }; registerFunction = () => { this.setState({ route: "registration" }); }; render() { ...

Can you explain the role of the faceVertexUV array within the three.js Geometry class?

Currently, I am utilizing three.js to create curved shapes using parametric functions. Within the THREE.js javascript file, there is a function called THREE.ParametricGeometry that continuously adds 2D vectors to the faceVertexUvs array. I am curious abo ...

Ways to attach dynamic methods within a v-for loop

I am currently working on a situation where I need to dynamically assign methods to elements that are being generated by a template using a v-for loop. These methods will be assigned based on the value of a particular variable, specifically the 'btn.m ...

Ways to examine a JavaScript Bound Function

Can a JavaScript bound function be inspected somehow? I need to be able to return a bound function from a function, and when unit testing, I'd like to verify the bound function's target, boundThis, and boundArgs. These properties seem to be inte ...

The X-Editable Bootstrap field is activated exclusively on the initial hyperlink click

Utilizing Bootstrap X-Editable in conjunction with bootstrap-wysihtml5. On each post page, there is a list of comments with an edit link beneath them. However, only the first comment on the latest (most recently submitted) post can be edited using the X- ...

JavaScript: Splitting strings with multiple delimiters

Can I use a Java Script function to divide a string into multiple parts? var string = "This is a test text, again, this is a testing text"; For instance, I can split the string using , like this: string.split(','); resulting in: var string = [ ...

Accessing the nested arrays within an ng-repeat loop

Can anyone help me figure out what I'm doing incorrectly here? I've fetched some data and passed it to a controller as 'productInfo'. While I can successfully load the data, I am encountering issues when trying to target specific valu ...

Tips for sharing invites with friends through the Facebook instant game SDK using the Phaser framework

Currently, I am in the midst of developing a Facebook instant game project. It has come to my attention that I need to include friend invites in my instant game, which is built using the Phaser framework. Unfortunately, after conducting a thorough search, ...

Displaying JSON data on an HTML page

i am currently developing a web application and i am facing an issue with retrieving data from JSON files and displaying them in table format. The problem arises when i encounter a 404 error, as i am working locally using Node.js. Edit 1: upon checking ...

Getting a portion of a href link in Java using Selenium

I am looking to compare the current URL in Google Chrome with a specific href link that contains two URLs. I need to extract the first link from this specific href link: click here <a href="http://pubcontentqa.perion.com/dz2/html/interstitial.html?http ...

Problem regarding data-th-id

I am facing an issue with a button that triggers a modal view and trying to capture its value using JavaScript. Here is how it's set up: <button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal" data-target="#myModal" d ...