如何在Jest测试中模拟全局自定义window对象?
在Jest测试中模拟全局
component对象的解决方案 问题根源
你之前的beforeAll里仅定义了局部的component变量,并未将其挂载到全局作用域(对应浏览器环境的window对象),而待测试模块直接依赖全局的component变量,因此测试时会抛出ReferenceError。另外,若测试文件顶部直接导入模块,模块会在beforeAll执行前就加载,此时全局component还未定义,也会触发报错。
解决方案
方法1:在测试文件中动态挂载全局对象并延迟导入模块
修改你的helpers.test.js,将模拟的component挂载到window(Jest中window等价于global),并在挂载完成后再导入待测试模块:
let getShift; beforeAll(() => { // 模拟全局的component变量 window.component = { clientTimeZoneShiftInMinutes: 180, }; // 动态导入模块,确保component已挂载后再加载 ({ getShift } = require('./你的模块文件路径')); }); test("Choosing correct shift", () => { // 注意:getDate接收的是Date对象,需传入实例而非字符串 expect(getShift(new Date("2022-12-22T00:00:01"))).toBe(1); });
方法2:通过Jest全局配置文件预挂载模拟对象
如果多个测试文件都需要用到这个全局component,可以通过Jest的配置文件统一挂载:
- 创建
jest.setup.js文件,写入全局模拟代码:
window.component = { clientTimeZoneShiftInMinutes: 180, };
- 在
jest.config.js中配置setupFiles,让Jest在加载测试文件前先执行这个配置:
module.exports = { setupFiles: ['./jest.setup.js'], // 其他Jest配置... };
- 此时测试文件可以直接导入模块,无需再在
beforeAll中处理:
import { getShift } from './你的模块文件路径'; test("Choosing correct shift", () => { expect(getShift(new Date("2022-12-22T00:00:01"))).toBe(1); });
补充说明
- 若你的模块实际依赖的是
window.externalFunctions.component(即全局component来自window.externalFunctions),则需要调整模拟代码为:
window.externalFunctions = { component: { clientTimeZoneShiftInMinutes: 180, }, };
- 测试时务必传入
Date对象而非字符串,否则getDate中的date.setTime会抛出类型错误。
内容的提问来源于stack exchange,提问作者Mike M.
相关产品推荐
相关产品推荐

