Home > Mobile >  RTL test a button onClick prop
RTL test a button onClick prop

Time:11-27

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;

CodePudding user response:

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();
})
  • Related