[SOLVED] Unable to spyon click on button using jest and react testing library for a component testcase

Issue

Hi I am new to React testing library, I tried to write a test case but not getting desired result in test case. Need some guidance. On executing npm run test its showing expected number of calls >=1, received number of calls 0

Below is my code snippet——
Lgin.ts

import React,{SyntheticEvent} from 'react'


const Lgin: React.FC = ()=> {

const handleClick = (e: SyntheticEvent)=>{
console.log('hello');

}

return (
<>
<button  data-testid='btn1' type='button' onClick={handleClick}>hello</button>
</>
);

}
export default Lgin;

Lgin.test.ts

 import {render,screen,fireEvent} from '@testing-library/react' 
 import Lgin from './component'

descritbe('Lgin',()=>{
  
it('check button is clicked',()=>{
 render(<Lgin />)
 const clkev = jest.fn()
 let btnObj = screen.getByTestId('btn1');
 jest.spyOn(btnObj,'click').mockImplementation(()=>clkev);
 fireEvent.click(btnObj);
 expect(clkev).toHaveBeenCalled();
 })


)


)

Solution

Hi the reference given by @slideshowp2 worked, also following script worked for me:

    const mockFn =jest.spyOn(global.console,'log').mockReturnThis()
    fireEvent.click(screen.getByTestId("loginbutton"))
    expect(mockFn).toHaveBeenCalled()

Answered By – SCM

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *