How to write Unit testing (RTL) for a custom onClick function, where this onClick funtion sending as a prop to React Component?

Viewed 18
import React from "react";
import "./ToasterActionMessage.css";

const ToasterActionMessage = (props) => {

function retryFunction() {      
    if(props.onRetry) {
        const{onRetry} = props;
        onRetry();
    }    
}

if (props.action) {
    return (
      <div className="ToasterActionMessage-Card" style={{background: "#A00E18" }}>
        <div className=ToasterActionMessage-Side-body">
          <p className="ToasterActionMessage-Message">
            {props.message}
          </p>
          <div className="ToasterActionMessage-btn-text" onClick={retryFunction}>Retry</div>
        </div>
      </div>
    );
  }

  return null;
};

export default ToasterActionMessage;

the above is component which has onClick funciton as a prop and that works as expected.


while writing the unit testing, not able to click that Component?Somewhere i couldn't able to call that component. the below is the code

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

test("renders Retry - Onclick function of ToasterActionMessage component", ()=>{
    const mockOnclickFunction = jest.fn()
    render(<ToasterActionMessage action="true" onClick={mockOnclickFunction}/>)
    userEvent.click(screen.getElementsByText("Retry"))
    expect(mockOnclickFunction).toBeCalled();
})

Response :- No calls occured

Hope the error is while screening the component, not able to call the component, tried in mulitple ways by usning, getElementsByText, getElementsByclassName, id etc.. somewhere its going wrong, please help to figure it out.

0 Answers
Related