Angular 14升级至15后测试报错:__webpack_require__(...).context is not a function
Angular 14升级至15后
ng test报错__webpack_require__(...).context is not a function的解决方法 问题原因
Angular 15默认适配Webpack 5,而require.context是Webpack 4的专属API,Webpack 5已不再兼容该写法,因此原test.ts中的测试文件加载逻辑会触发报错。
解决方案
1. 替换test.ts中的require.context为Webpack 5兼容写法
将test.ts中加载测试文件的代码替换为Webpack 5支持的import.meta.glob:
原代码段:
// Then we find all the tests. const context: any = require.context("./", true, /\.spec\.ts$/); // And load the modules. context.keys().map(context);
替换为:
// 自动加载所有.spec.ts测试文件 const modules = import.meta.glob('./**/*.spec.ts', { eager: true });
修改后的完整test.ts示例:
import "zone.js/testing"; import { getTestBed } from "@angular/core/testing"; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from "@angular/platform-browser-dynamic/testing"; // 初始化Angular测试环境 getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); // 自动加载所有.spec.ts测试文件 const modules = import.meta.glob('./**/*.spec.ts', { eager: true });
2. 修复第三方库dhtmlx gantt的测试报错
移除test.ts后出现的dhtmlx报错,是因为测试环境缺少必要的全局依赖或初始化逻辑,可通过以下方式解决:
- 全局模拟dhtmlx对象(推荐,避免加载真实库):
在test.ts末尾添加模拟代码,覆盖测试所需的关键方法:
// 模拟dhtmlx gantt全局对象,适配测试环境 (window as any).gantt = { init: () => {}, attachEvent: () => {}, parse: () => {}, // 根据项目中使用的gantt方法补充模拟实现 };
- 引入真实dhtmlx脚本:
若需要在测试中使用真实库,修改karma.conf.js的files数组,添加dhtmlx的脚本路径:
module.exports = function(config) { config.set({ // 其他配置... files: [ 'node_modules/dhtmlx-gantt/codebase/dhtmlxgantt.js', // 若需要样式也可添加对应的css文件 'node_modules/dhtmlx-gantt/codebase/dhtmlxgantt.css' ] }); };
3. 验证配置正确性
确保angular.json中测试配置的builder为官方默认的@angular-devkit/build-angular:karma,避免自定义Webpack配置干扰:
{ "projects": { "your-project-name": { "architect": { "test": { "builder": "@angular-devkit/build-angular:karma", // 其他配置... } } } } }
内容的提问来源于stack exchange,提问作者himtim
相关产品推荐
相关产品推荐

