如何使用react-testing-library和jest测试mock自定义React hook的更新逻辑
解决方案
你可以通过将useRouter的mock实现指向可动态修改的Jest mock函数,配合renderHook提供的rerender方法实现需求,完整可运行的测试代码如下:
第一步:全局mock useRouter
首先在测试文件顶部做全局mock,将useRouter替换为Jest mock函数:
import { renderHook } from '@testing-library/react-hooks'; import Router from 'next/router'; import { useCustomHook } from './你的hook文件路径'; // 全局mock useRouter jest.mock('next/router', () => ({ useRouter: jest.fn() })); // mock helperFunction方便统计调用次数 jest.mock('./你的helperFunction所在文件路径', () => ({ helperFunction: jest.fn() }));
第二步:编写测试用例
利用mockImplementation动态修改返回值,配合rerender触发hook重执行,验证调用次数:
describe('useCustomHook', () => { // 每次测试前重置mock调用状态,避免用例互相干扰 beforeEach(() => { jest.clearAllMocks(); }); it('query更新n次时,helperFunction会被调用n次', () => { const helperFunction = require('./你的helperFunction所在文件路径').helperFunction; // 第一次query值 const firstQuery = { id: '1' }; (Router.useRouter as jest.Mock).mockImplementation(() => ({ route: '/', pathname: '', query: firstQuery, asPath: '', })); // 首次渲染hook const { rerender } = renderHook(() => useCustomHook()); // 首次渲染后helperFunction应该被调用1次 expect(helperFunction).toHaveBeenCalledTimes(1); expect(helperFunction).toHaveBeenCalledWith(firstQuery); // 第二次更新query const secondQuery = { id: '2' }; (Router.useRouter as jest.Mock).mockImplementation(() => ({ route: '/', pathname: '', query: secondQuery, asPath: '', })); // 触发hook重渲染 rerender(); // 总调用次数应该为2次 expect(helperFunction).toHaveBeenCalledTimes(2); expect(helperFunction).toHaveBeenCalledWith(secondQuery); // 第三次更新query const thirdQuery = { id: '3', keyword: 'test' }; (Router.useRouter as jest.Mock).mockImplementation(() => ({ route: '/', pathname: '', query: thirdQuery, asPath: '', })); rerender(); // 总调用次数为3次 expect(helperFunction).toHaveBeenCalledTimes(3); expect(helperFunction).toHaveBeenCalledWith(thirdQuery); }); })
原理解释
- 全局mock时将
useRouter替换为Jest的mock函数,支持在测试过程中随时通过mockImplementation修改返回值 renderHook返回的rerender方法会重新执行你的自定义hook,触发内部useEffect的依赖比对,当query发生变化时就会执行对应回调- 每次修改
useRouter的返回值后调用rerender,即可模拟路由query更新的场景,验证helperFunction的调用次数是否符合预期
内容的提问来源于stack exchange,提问作者user10741122
相关产品推荐
相关产品推荐

