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

107
Views
react testing library toHaveBeenCalled 0 mocking a simple click prop

I try to mock a prop called actionClicked but my test failed, I have a simple component as below

const ButtonAction: React.FC = ({ actionClicked }) => {
    const handleClick = (action) => () => actionClicked(action)
  
    return (
          <div
            data-testid="some-action"
            onClick={handleClick('something')}
          >
              <Icon />
          </div>
    )
  }

this is my test, button.spec.tsx

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

import React from 'react'

import ButtonAction from './ButtonAction'

test('render ButtonAction', () => {
  const actionClicked = jest.fn()

  render(<ButtonAction actionClicked={actionClicked} />)

  userEvent.click(screen.getByTestId('some-action'))
  expect(actionClicked).toHaveBeenCalled() //failed here
})

I'm not sure why actionClicked is not been called.

Expected number of calls: >= 1
Received number of calls:    0

Any thoughts?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This behaviour occurs because userEvent.click returns a promise.

First you should turn your test to async and then await userEvent.click:

test("render ButtonAction", async () => {
  const actionClicked = jest.fn();

  render(<ButtonAction actionClicked={actionClicked} />);

  await userEvent.click(screen.getByTestId("some-action"));

  expect(actionClicked).toHaveBeenCalledTimes(1);
});

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!