Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

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

7 months 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);
});

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs