I have a Component and want to unit test it with react jest... I want to test onClick event.. I've tried many cases but they don't cover onClick statement
This my Component
export default class HeaderCreate extends Component {
render() {
const { name, description, closeRightSection } = this.props;
return (
<div className="header">
<h1 className="header-text" title={name} data-testid="header">{name}</h1>
<p data-testid= "description-para">{description}</p>
<Tooltip title="Close Section">
<div className="icon-close">
<i className="material-icons" onClick={() => closeRightSection()} data-testid="id">close</i>
</div>
</Tooltip>
</div>
)
}
};
This is my test.js
import React from 'react'
import { render } from "@testing-library/react";
import HeaderCreate from '../components/createHeader';
test("render header correctly", () => {
const { getByTestId } = render(<HeaderCreate name="My Name is Test"></HeaderCreate>);
expect(getByTestId('header').textContent).toBe('My Name is Test')
});
test("render Description Paragraph correctly", () => {
const { getByTestId } = render(<HeaderCreate description="Hi I am Description box"></HeaderCreate>);
expect(getByTestId('description-para').textContent).toBe('Hi I am Description box')
});
test("render close tooltip correctly", () => {
const { getByTestId } = render(<HeaderCreate closeRightSection=""></HeaderCreate>);
expect(getByTestId('id')).toBeTruthy();
});
In Coverage it is show all onClick event as statement not covered.. and statement coverage is 66.67%. How can I make it 100%..? I am new to Reactjs. So I am Confused what to do now.. I have search on various place but didn't got any solution. Please suggest me where I am wrong
Thanks in advance
It looks like you need to write a test to simulate clicking on the i
element. You can accomplish this with the fireEvent
helper from RTL. Create a mock callback to pass in props, target the id
test id and simulate a click and assert the callback was called.
import { render, fireEvent } from '@testing-library/react';
...
test("should call closeRightSection callback", () => {
const closeRightSectionSpy = jest.fn();
const { getByTestId } = render(
<HeaderCreate closeRightSection={closeRightSectionSpy} />
);
fireEvent.click(getByTestId('id'));
expect(closeRightSectionSpy).toHaveBeenCalled();
});