'Unable to spyon click on button using jest and react testing library for a component testcase
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 1:[1]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SCM |
