如何通过Jest预加载JavaScript依赖?能否无需导入直接注入依赖?
如何通过Jest或其他方式注入未导入的依赖
lib? 目标文件file.js中直接调用了未定义也未导入的lib方法,尝试通过Jest的globals配置、setupFiles注入均无效,报错提示lib is not defined,以下是问题详情和解决方法:
问题代码示例
示例 file.js
// Note: lib is not defined in this file export const getDep = (str) => { lib('something'); return str; }
示例 jest.config.js
module.exports = { globals: { window: { lib: () => {} // 无效 }, lib: () => {} // 无效 }, setupFiles: ['<rootDir>/jest/setupFiles.js'], // 同样无效 // ...其他配置 }
示例 jest/setupFiles.js
const lib = () => {}; console.log(lib);
示例 file.test.js
import { getDep } from "file.js"; describe('Test injection of global dependency using jest.config', () => { it("should not break test", () => { const result = getDep('hello'); expect(result).toEqual('hello') }) })
执行测试时的错误
Error ReferenceError: lib is not defined
1 | 2 | export const getDep = (str) => { > 3 | lib('something'); | ^ 4 | return str;
解决方法
方法1:在setupFiles中挂载到全局对象
之前的setupFiles.js只是定义了局部变量,并没有将lib挂载到全局作用域。修改jest/setupFiles.js,将lib绑定到Node.js的全局对象global(或用globalThis兼容多环境):
// jest/setupFiles.js global.lib = () => {}; // 兼容浏览器/Node环境的写法: // globalThis.lib = () => {};
确保jest.config.js中的setupFiles路径正确,之后Jest会在测试执行前加载这个文件,全局的lib就会被目标文件识别。
方法2:在测试文件中直接注入全局依赖
在导入目标文件之前,直接在测试文件中定义全局的lib,还可以用Jest的mock函数来验证调用情况:
// file.test.js // 先定义全局lib global.lib = jest.fn(); import { getDep } from "./file.js"; describe('测试全局依赖注入', () => { it("执行不报错并返回正确结果", () => { const result = getDep('hello'); expect(result).toEqual('hello'); // 还能验证lib是否被正确调用 expect(lib).toHaveBeenCalledWith('something'); }) })
方法3:使用Jest的globals配置正确赋值
如果想用jest.config.js的globals配置,需要确保直接赋值顶级全局变量,而不是嵌套在window里(Node测试环境下没有window对象):
// jest.config.js module.exports = { globals: { lib: () => {} // 直接定义顶级全局变量 }, // ...其他配置 }
注意:这种方式在某些ES模块环境下可能需要配合transform配置(比如@babel/preset-env)才能生效,不如前两种方法稳定。
内容的提问来源于stack exchange,提问作者Inspiraller
相关产品推荐
相关产品推荐

