Jest mock已弃用npm request模块post方法遇TypeError,如何正确实现测试模拟
问题根因排查
你遇到的报错和测试逻辑不对的核心原因有三个:
- 测试文件没有导入完整的
request模块对象,只通过命名导入拿到了解构出来的post方法,代码里访问的request变量不存在,自然报Cannot set property 'post' of undefined的错 - 对
request.post的调用形式理解错误:这个方法是错误优先的回调风格接口,不是返回Promise的API,之前mock成Promise.resolve的写法完全匹配不上业务代码传回调的调用逻辑 - 原业务代码的回调处理结果没有被向外返回,直接依赖函数返回值做断言根本拿不到异步执行的回调结果
正确的Mock实现方案
基础配置
首先在测试文件最顶部,所有导入语句之前对request模块做全局打桩,不要在测试用例里直接修改模块的属性:
// 测试文件顶部 jest.mock('request', () => ({ post: jest.fn() })); // 后续正常导入模块 import { post } from 'request'; import { functionToFetch } from './example';
这个写法的好处是:Jest会自动替换真实的request模块,把它的post方法变成可控的mock函数,不会真的发起网络请求。
分场景编写测试用例
因为post是回调风格,每次mock的时候我们需要手动触发它收到的回调参数,传入模拟的错误、响应、返回体,就能精准触达业务代码里的分支逻辑。
1. 模拟请求错误场景
it('should execute error branch when request fails', () => { // 构造模拟的网络错误 const mockError = new Error('Connection refused'); // 清空上一次测试留下的mock调用记录 post.mockClear(); // 定义post的mock实现:收到调用时立即执行传入的回调 post.mockImplementation((requestOptions, callback) => { // 直接执行回调,传入错误值、空响应、空返回体 callback(mockError, {}, null); }); // 监听console.log的调用,验证错误分支执行 const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); // 调用业务函数 functionToFetch('http://test-endpoint.com'); // 断言post被正确调用 expect(post).toHaveBeenCalledWith( expect.objectContaining({ url: 'http://test-endpoint.com', headers: {}, json: expect.anything() }), expect.any(Function) ); // 断言错误分支的日志被打印 expect(logSpy).toHaveBeenCalledWith('error'); logSpy.mockRestore(); });
2. 模拟请求成功场景
it('should execute success branch when request succeeds', () => { // 构造模拟的成功响应 const mockResponse = { statusCode: 200 }; const mockBody = { data: 'fetch success' }; post.mockClear(); post.mockImplementation((requestOptions, callback) => { // 触发回调,传入空错误、成功响应、业务返回体 callback(null, mockResponse, mockBody); }); functionToFetch('http://test-endpoint.com'); // 这里可以根据业务代码里的成功逻辑,补对应的断言 expect(post).toHaveBeenCalledWith( expect.objectContaining({ url: 'http://test-endpoint.com' }), expect.any(Function) ); });
常见踩坑提醒
- 不要把成功、失败两个分支的测试写在同一个测试块里,否则mock的状态会互相污染,导致测试结果不稳定
- 原业务代码存在语法错误:
console.log('error)缺少闭合的单引号,会导致运行直接报错 - 如果后续需要对业务函数的返回值做断言,需要把回调形式的逻辑用Promise包装起来,因为当前写法下回调是异步执行的,函数的return值并不是回调里的处理结果
内容的提问来源于stack exchange,提问作者Dujard
相关产品推荐
相关产品推荐

