Ionic应用测试时Jasmine/Karma无法忽略node_modules中spec文件
解决Ionic应用测试时node_modules文件导入错误的方案
解决这个问题可以通过以下几个配置调整,彻底排除node_modules中的文件,避免测试时加载到依赖包内的spec或源码文件:
1. 修改tsconfig.spec.json,明确排除node_modules
在配置文件中添加exclude字段,强制编译器只处理src目录下的测试文件:
/* To learn more about this file see: https://angular.io/config/tsconfig. */ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": [ "jasmine" ] }, "files": [ "src/test.ts", "src/polyfills.ts" ], "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ], "exclude": [ "node_modules/**/*", "**/*.spec.ts" ] }
2. 调整karma.conf.js,排除node_modules文件
在Karma配置中添加exclude数组,防止测试 runner 加载依赖包内的文件:
// 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'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage'), require('@angular-devkit/build-angular/plugins/karma') ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, jasmineHtmlReporter: { suppressAll: true // removes the duplicated traces }, coverageReporter: { dir: require('path').join(__dirname, './coverage/ngv'), subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ] }, reporters: ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, restartOnFileChange: true, // 添加排除规则 exclude: [ 'node_modules/**/*' ] }); };
3. 验证angular.json的测试配置
确认现有配置中assets仅指向src目录资源,你的当前配置已符合要求,无需修改:
"assets": [ { "glob": "favicon.ico", "input": "src/", "output": "/" }, { "glob": "**/*", "input": "src/assets", "output": "/assets" }, "src/manifest.webmanifest" ]
额外排查步骤
- 清理Angular缓存:
ng cache clean - 重装依赖:
rm -rf node_modules package-lock.json npm install - 重新启动测试:
ng test
内容的提问来源于stack exchange,提问作者NegriHenrique
相关产品推荐
相关产品推荐

