What is the process for creating a unit test case for a button's onClick event with Jest?

In my attempt to unit test the onClick event of a button in a component, I encountered some challenges. Specifically, I am unsure how to properly test the onClick event when it triggers a function like Add(value).

App.js

function App(){
   const[value,setValue] = useState('')
   const[list,setList] = useState([])

   function Add(el){
      let updatedList = [...list,el]
      setList(updatedList)
   }

   return(
<div>
   <input data-testid="inpField" type="text" onChange={(e)=>setValue(e.target.value)}
   <button data-testid="btn" onClick={()=>Add(value)}>Add</button>
   {list.map((post,index) => <li key={index}>{post}</li>)}
</div>
)

I've attempted the following approach, but encountered an error - Expected number of calls: >=1 but received number of calls: 0

App.test.js

test('btn click',()=>{
const Add = jest.fn()
render(<App/>)
const button = screen.getByTestId('btn')
fireEvent.click(button)
expect(Add).toHaveBeenCalled()
})

All necessary imports are assumed to have been completed. P.S.:- I prefer not to use enzyme unless absolutely necessary.

Answer №1

The issue with the error message

Expected number of calls: >=1 but received number of calls :0
is due to not invoking the mock function that was created. To ensure the mock function is invoked, it should be passed as a prop to the App component like so:

function App({Add}){
   const[value,setValue] = useState('')
   const[list,setList] = useState([])

   return(
<div>
   <input data-testid="inpField" type="text" onChange={(e)=>setValue(e.target.value)}
   <button data-testid="btn" onClick={()=>Add(value)}>Add</button>
   {list.map((post,index) => <li key={index}>{post}</li>)}
</div>
)

App.test.js:

test('btn click',()=>{
const Add = jest.fn()
render(<App Add={Add}/>)
const button = screen.getByTestId('btn')
fireEvent.click(button)
expect(Add).toHaveBeenCalled()
})

This adjustment will make the test case pass successfully.

If you want to specifically test the onClick method for adding an item to the list, modify the test case as follows:

test('btn click',()=>{
render(<App/>)
const inputField = screen.getByTestId('inpField');
fireEvent.change(inputField, { target: { value: 'New Item #1' } });

const button = screen.getByTestId('btn')
fireEvent.click(button)

expect(screen.getByText('New Item #1')).toBeInTheDocument()
})

This revised test validates the functionality of your on-click logic. It inputs text into the field, clicks the button, and then checks if the inputted item is displayed on the document.

I trust this explanation helps clarify things.

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

Adjust the color of the active link on the page using Angular and CSS

I have a project that I need to modify by adding a sub menu that appears on every page but is only coded once. My goal is to highlight the link for the current page, all within one HTML snippet. Although the list renders correctly, I'm struggling to g ...

When a single object is entered, JSON returns 'undefined', however, it works successfully when using the .map() function

Utilizing Axios to fetch data from DeezerAPI, I initially rendered information using .map() and everything worked smoothly when passing it to a Component. However, when attempting to access a single JSON object, I encountered an 'undefined' error ...

Flipping Cards with Material-UI

The documentation for React Material-UI's Card component mentions that it does not have a built-in feature to flip over and reveal more information on the back. However, I am curious if anyone has found a workaround or used other libraries to achieve ...

Prevented a frame from "https://googleads.g.doubleclick.net" from accessing another frame

After placing ads on my website, they are displaying properly. However, I am receiving an error repeatedly in the console when the page loads: A frame from origin "" is being blocked from accessing a frame with origin "". The requesting frame has an "ht ...

Creating a sort button in HTML that can efficiently sort various divs within a table is a useful tool for enhancing user experience

My HTML table is populated with various <td> elements. How can I arrange these divs based on IMDb rating, TomatoMeter, etc... [ CSS code is not provided below ] <table> <tr class="row"> <td class="column"> <br> ...

When converting to TypeScript, the error 'express.Router() is not defined' may

Currently, I am in the process of converting my express nodejs project from JavaScript to TypeScript. One of the changes I've made is renaming the file extension and updating 'var' to 'import' for "require()". However, there seems ...

Ensuring AngularJS ui-router/app waits for $http data to avoid Flash of Unstyled Content (FOUC)

My question or situation pertains to the states defined in my AngularJS application. Here is an example of how I have them structured: $stateProvider .state('myApp', { abstract: true, template: '& ...

Create a URL hyperlink using javascript

I am looking to create a link to a page that updates its URL daily. The main URL is where X represents the day of the month. For example, for today, July 20th, the link should read: In my JavaScript section, I currently have code that retrieves the cur ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...

tips for optimizing javascript file caching

https://i.stack.imgur.com/UhWD1.pngMy web application was created using "pug" technology about 9-8 years ago, and more recently, pages have been added in an innovative framework (vue.js). However, whenever there is a transition between an old pug page and ...

What techniques can I utilize to ensure Azure function generates JSON specifically for web browsers?

I have a functioning Azure function with the following code: module.exports = function(context, req) { // this is the complete source code, believe it or not context.done(null, {favoriteNumber: 3}); }; When I utilize a tool like Postman to access ...

date selection event

Utilizing the DatePicker feature from Material UI v0, I have crafted a distinct component called DateField to showcase the DatePicker. Here is how it looks: render() { return ( <div> <DatePicker onChange={this.onChang ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

The res.sendFile() function quickly delivers a 204 no content response

Currently, I am facing an issue with using Express' sendFile() function to send an image. The function does not seem to read my file at all and instead returns a 204 no-content response. Below is the code for my function/endpoint: @httpGet('/pri ...

Playing audio from local blob data is not supported on mobile browsers

I'm trying to stream blob data in mp3 format, but I'm experiencing difficulties with mobile browsers. The code below works perfectly on PC browsers, but not on mobile: // Javascript var url = URL.createObjectURL(blob); audio = document.getEleme ...

Ways to retrieve a value within a function and update a variable

Fetching data from the firebase database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ console.log('Error!'); console.log(err); } function gotData(d ...

The technique for handling intricate calls in node.js

My goal is to create a social community where users are rewarded for receiving upvotes or shares on their answers. Additionally, I want to send notifications to users whenever their answers receive some interaction. The process flow is detailed in the com ...

The email validation function is not functioning correctly when used in conjunction with the form submission

I'm currently working on my final project for my JavaScript class. I've run into a bit of a roadblock and could use some guidance. I am trying to capture input (all code must be done in JS) for an email address and validate it. If the email is va ...

React component showcasing live data based on the URL's input

I'm looking to develop a dynamic component that can retrieve and display data from a JSON file based on the URL path, rather than creating separate pages for each dataset. For instance: https://jsonplaceholder.typicode.com/posts If the page route is ...

NodeJS Streams: Delay in data transfer with Readable.pipe()

My understanding was that Stream.Readable.pipe() would immediately pipe data as it receives it, but I'm facing unexpected results while trying to create my own streams. const { Writable, Readable } = require("stream"); const writable = new ...