Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RTL test a button onClick prop

I am following the RTL docs and want to test my button component. I can’t seem get my test to pass for the onclick. I have mocked the onClick function but I am getting the below error.

I am following this guide

expect(jest.fn()).toHaveBeenCalledTimes(expected)

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

import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'

import Button from "../Button/Button"

const handleClick = jest.fn();

describe('Button', () => {
    beforeEach(() => {

        render(
            <Button
                onClick={handleClick}
            >
                buttonText
            </Button>
        )
    })

    it('should render button text', () => {
        const buttonText = "buttonText"
        expect(screen.getByText(buttonText)).toBeInTheDocument()
    })

    it('calls onClick prop when clicked', () => {
        const handleClick = jest.fn();
        const buttonText = "buttonText"
        fireEvent.click(screen.getByText(buttonText))
        expect(handleClick).toHaveBeenCalledTimes(1)
    })
})

import React from "react";

import { PrimaryButton } from "./Button.styles";

const Button = ({ onClick, children }) => (
    <PrimaryButton
        type="button"
        onClick={onClick}
    >
        {children}
    </PrimaryButton>
);

export default Button;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t want to be resetting handleClick inside the test or else you’ll lose reference to the actual click handler mock that you’ve declared in the higher scope.

it('calls onClick prop when clicked', () => {
  const buttonText = "buttonText"
  fireEvent.click(screen.getByText(buttonText))
  expect(handleClick).toHaveBeenCalledTimes(1)
})

You may also need to reset the click count between tests. You can do this with clearAllMocks:

afterEach(() => {
  jest.clearAllMocks();
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading