Angular17+Jasmine+Karma报错:Uncaught ReferenceError: require未定义
Angular 17 + Jasmine/Karma 单元测试:
Uncaught ReferenceError: require is not defined 问题排查 我在使用Angular 17结合Jasmine与Karma执行单元测试时,持续遇到Uncaught ReferenceError: require is not defined错误,导致测试无法正常推进。尝试过网络上多数可行方案及相关建议,包括启用karma.conf.js中注释的修复代码,均未解决问题。同时不确定测试环境的target应设为"web"还是"node",也不清楚如何实现SSR模式下的测试。
现有配置文件
karma.conf.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: [ 'jasmine', '@angular-devkit/build-angular', 'browserify', ], plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-jasmine-html-reporter', 'karma-coverage', 'karma-junit-reporter', 'karma-browserify', '@angular-devkit/build-angular/plugins/karma', '@angular-builders/custom-webpack/dist/karma' ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, // preprocessors: { // // '**/*.js': ['browserify'], // Apply browserify to your test files // "**/*.spec.js": ["browserify"] // }, // webpack: { // // Add webpack configuration options here // module: { // rules: [ // { // test: /\.js$/, // use: { // loader: 'babel-loader', // options: { // presets: ['@babel/preset-env'] // } // } // } // ] // } // }, // files: [ // {pattern: '**/*.spec.js', included: false}, // ], coverageReporter: { dir: require('path').join(__dirname, './coverage'), type: 'lcov', subdir: '.', reports: ['html', 'lcovonly', 'text-summary'], fixWebpackSourcePaths: true, check: { global: { statements: 80, branches: 80, functions: 80, lines: 80 } } }, reporters: ['progress', 'junit', 'kjhtml','coverage'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromiumHeadless', flags: ['--no-sandbox'] } }, junitReporter : { outputDir : './junit/test-reports' }, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true, customWebpackConfig: { // Point to your custom Webpack config here path: './webpack.config.js' } }); };
webpack.config.js
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin'); module.exports = { externalsPresets: { node: true }, // Keep this to avoid node-relevant errors target: 'node', // Ensure you're targeting the web environment plugins: [ new NodePolyfillPlugin() // Add the polyfill plugin ], externals: { 'fs': 'commonjs fs' // Prevents Webpack from bundling `fs` } };
问题分析与修复方案
1. 核心问题定位
require is not defined错误的核心原因是测试环境混淆了Node.js与浏览器环境:Karma运行在浏览器中,而当前Webpack配置设置了target: 'node',会导致Webpack打包出适配Node.js的代码,其中包含require等Node.js特有的模块语法,浏览器无法识别。
2. 关键配置调整
调整Webpack配置
修改webpack.config.js,将目标环境改为浏览器,并移除Node.js相关的预设与外部依赖:
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin'); module.exports = { target: 'web', // 明确目标为浏览器环境 plugins: [ new NodePolyfillPlugin() // 仅在确实需要Node.js API polyfill时保留,否则可移除 ] // 移除Node.js相关配置 // externalsPresets: { node: true }, // externals: { // 'fs': 'commonjs fs' // } };
清理Karma配置中的冲突项
Karma结合Angular官方的@angular-devkit/build-angular时,不需要额外引入browserify框架和插件——Angular已经自带Webpack打包流程,两者共存会导致打包逻辑冲突:
修改karma.conf.js的frameworks和plugins:
frameworks: [ 'jasmine', '@angular-devkit/build-angular' // 移除 'browserify' ], plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-jasmine-html-reporter', 'karma-coverage', 'karma-junit-reporter', '@angular-devkit/build-angular/plugins/karma' // 移除 'karma-browserify' 和 '@angular-builders/custom-webpack/dist/karma'(若无需自定义Webpack) ], // 若无需自定义Webpack,移除以下配置 // customWebpackConfig: { // path: './webpack.config.js' // }
3. SSR模式测试说明
如果需要测试SSR相关代码,应将测试拆分为两类场景:
- 浏览器端测试:使用Karma,目标环境设为
web,专注测试客户端组件逻辑。 - Node.js端测试:直接使用Jasmine或Jest运行在Node.js环境中,测试服务器端渲染的逻辑,此时Webpack的
target设为node是合理的。
内容的提问来源于stack exchange,提问作者Terry Windwalker
相关产品推荐
相关产品推荐

