无法使用组件测试用例的开玩笑和反应测试库来监视单击按钮
Unable to spyon click on button using jest and react testing library for a component testcase
嗨,我是 React 测试库的新手,我尝试编写一个测试用例,但在测试用例中没有得到预期的结果。需要一些指导。在执行 npm 运行 测试时,它显示预期的调用次数 >=1,收到的调用次数 0
下面是我的代码片段------
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>
</>
);
}
导出默认 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();
})
)
)
您好,@slideshowp2 提供的参考有效,以下脚本对我也有效:
const mockFn =jest.spyOn(global.console,'log').mockReturnThis()
fireEvent.click(screen.getByTestId("loginbutton"))
expect(mockFn).toHaveBeenCalled()
嗨,我是 React 测试库的新手,我尝试编写一个测试用例,但在测试用例中没有得到预期的结果。需要一些指导。在执行 npm 运行 测试时,它显示预期的调用次数 >=1,收到的调用次数 0
下面是我的代码片段------ 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>
</>
);
} 导出默认 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();
})
)
)
您好,@slideshowp2 提供的参考有效,以下脚本对我也有效:
const mockFn =jest.spyOn(global.console,'log').mockReturnThis()
fireEvent.click(screen.getByTestId("loginbutton"))
expect(mockFn).toHaveBeenCalled()