You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest中Mock外部脚本函数遭遇ReferenceError问题求助

解决Jest测试中Mock外部getUser函数的ReferenceError问题

你遇到的ReferenceError: getUser is not defined本质是作用域不匹配:你在测试脚本里声明的jest.fn()版本的getUser只存在于测试文件的局部作用域,而待测试脚本里调用的getUser是来自外部依赖的,两者完全不相关。下面根据不同的依赖引入方式给出针对性解决方案:

情况1:待测试脚本通过CommonJS(require)引入外部脚本

如果你的待测试脚本是这样引入getUser的:

// 待测试脚本 my-script.js
const { getUser } = require('./external-script');

function myFunction() {
  var session = getUser();
  // ...其他业务逻辑
}

module.exports = { myFunction };

可以用Jest的jest.mock()直接mock整个外部模块:

// 测试脚本 my-script.test.js
// 先mock外部模块,指定getUser的默认返回值
jest.mock('./external-script', () => ({
  getUser: jest.fn().mockReturnValue({ id: 1, name: 'Mocked Test User' })
}));

// 引入待测试脚本
const { myFunction } = require('./my-script');
// 引入mock后的getUser,方便断言调用情况
const { getUser } = require('./external-script');

test('should use mocked getUser to get session', () => {
  myFunction();
  
  // 断言getUser被调用过
  expect(getUser).toHaveBeenCalled();
  // 若函数有返回session相关结果,可继续断言
  // expect(myFunction()).toEqual({ id: 1, name: 'Mocked Test User' });
});

情况2:getUser是全局对象上的方法(比如浏览器环境的window)

如果getUser是挂载到全局对象上的(比如前端项目里的window.getUser),可以直接mock全局变量:

// 测试脚本
// 在引入待测试脚本前,给全局对象添加mock的getUser
global.getUser = jest.fn().mockReturnValue({ id: 1, name: 'Global Mock User' });

// 引入待测试脚本
require('./my-script');

test('should call global mocked getUser', () => {
  // 执行待测试脚本里的逻辑
  expect(getUser).toHaveBeenCalled();
});

情况3:待测试脚本使用ES模块(import)引入外部脚本

如果项目用的是ES模块(import/export),注意jest.mock要放在import之前:

// 测试脚本
// 先mock外部模块
jest.mock('./external-script', () => ({
  getUser: jest.fn().mockReturnValue({ id: 2, name: 'ES Module Mock User' })
}));

// 再导入待测试脚本和mock的函数
import { myFunction } from './my-script';
import { getUser } from './external-script';

test('should work with ES modules', () => {
  myFunction();
  expect(getUser).toHaveBeenCalled();
});

额外技巧:不同测试用例返回不同值

如果需要在不同测试用例里让getUser返回不同结果,只需在对应测试用例里重新设置mockReturnValue即可:

test('should handle admin user logic', () => {
  getUser.mockReturnValue({ id: 3, name: 'Admin', isAdmin: true });
  myFunction();
  // 断言管理员相关业务逻辑
});

test('should handle guest user logic', () => {
  getUser.mockReturnValue({ id: 4, name: 'Guest', isGuest: true });
  myFunction();
  // 断言访客相关业务逻辑
});

内容的提问来源于stack exchange,提问作者HOK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:48:12