如何为带参数的点击事件编写含toHaveBeenCalledWith的测试用例
如何用
toHaveBeenCalledWith测试带参数的点击事件组件 我有一个返回<a>标签的组件,该标签的点击事件会传入两个参数调用处理函数。请问如何使用toHaveBeenCalledWith编写对应的测试用例?
原组件代码:
export const TestCompo = (a, b) => { const handleClick = (param_1, param_2) => { // * do something }; return ( <a onClick={() => { handleClick(a, b); }} /> ); };
原测试代码片段:
element.find("a").at(0).simulate("click"); expect(jest.fn()).toHaveBeenCalledWith(); expect(jest.fn()).toBeCalledTimes(1);
解决方案
要测试内部函数的调用参数,核心是让测试代码能追踪到handleClick的调用情况,以下是两种常用实现方式:
方法1:将回调作为Props传入(推荐)
调整组件结构,让handleClick成为可传入的Props,这是更符合可测试性的设计:
export const TestCompo = ({ a, b, handleClick }) => { return ( <a onClick={() => { handleClick(a, b); }} /> ); };
对应测试用例:
import { shallow } from 'enzyme'; import { TestCompo } from './TestCompo'; describe('TestCompo', () => { it('点击a标签时,handleClick会传入正确的参数', () => { // 1. 创建jest mock函数 const mockHandleClick = jest.fn(); // 2. 定义测试用的参数 const testParamA = 'test-value-a'; const testParamB = 'test-value-b'; // 3. 渲染组件并传入参数和mock函数 const wrapper = shallow(<TestCompo a={testParamA} b={testParamB} handleClick={mockHandleClick} />); // 4. 模拟a标签的点击事件 wrapper.find('a').simulate('click'); // 5. 断言调用次数和参数正确性 expect(mockHandleClick).toHaveBeenCalledTimes(1); expect(mockHandleClick).toHaveBeenCalledWith(testParamA, testParamB); }); });
方法2:监视组件内部的handleClick函数
如果不想修改组件结构,可以导出内部函数并通过jest.spyOn监视它的调用:
// 修改组件,导出handleClick函数 export const handleClick = (param_1, param_2) => { // * do something }; export const TestCompo = (a, b) => { return ( <a onClick={() => { handleClick(a, b); }} /> ); };
对应测试用例:
import { shallow } from 'enzyme'; import { TestCompo, handleClick } from './TestCompo'; describe('TestCompo', () => { it('点击a标签时传入正确参数调用handleClick', () => { // 1. 监视handleClick函数,替换为mock实现 const clickSpy = jest.spyOn(require('./TestCompo'), 'handleClick').mockImplementation(() => {}); const testA = 'foo'; const testB = 'bar'; const wrapper = shallow(<TestCompo a={testA} b={testB} />); wrapper.find('a').simulate('click'); // 断言调用情况 expect(clickSpy).toHaveBeenCalledTimes(1); expect(clickSpy).toHaveBeenCalledWith(testA, testB); // 清理spy,避免影响其他测试 clickSpy.mockRestore(); }); });
内容的提问来源于stack exchange,提问作者kenpeter
相关产品推荐
相关产品推荐

