angular在单元测试时执行ng test --no-watch --code-coverage
报异常如下:
ERROR [karma-server]: UncaughtException: Error: spawn UNKNOWN
at ChildProcess.spawn (node:internal/child_process:414:11)
at spawn (node:child_process:761:9)
at spawnWithoutOutput (D:\Angular\node_modules\karma\lib\launchers\process.js:174:26)
at ProcessLauncher._execCommand (D:\Angular\node_modules\karma\lib\launchers\process.js:75:21)
at ProcessLauncher._start (D:\Angular\node_modules\karma\lib\launchers\process.js:33:10)
at Object.<anonymous> (D:\Angular\node_modules\karma\lib\launchers\process.js:19:10)
at Object.emit (node:events:529:35)
at BaseLauncher.start (D:\Angular\node_modules\karma\lib\launchers\base.js:52:10)
at Object.j (D:\Angular\node_modules\karma\lib\launcher.js:108:17)
at setTimeout.bind.j (D:\Angular\node_modules\qjobs\qjobs.js:143:18)
ERROR [karma-server]: Error: spawn UNKNOWN
at ChildProcess.spawn (node:internal/child_process:414:11)
at spawnWithoutOutput (D:\Angular\node_modules\karma\lib\launchers\process.js:174:26)
at ProcessLauncher._execCommand (D:\Angular\node_modules\karma\lib\launchers\process.js:75:21)
at ProcessLauncher._start (D:\Angular\node_modules\karma\lib\launchers\process.js:33:10)
at Object.<anonymous> (D:\Angular\node_modules\karma\lib\launchers\process.js:19:10)
at Object.emit (node:events:529:35)
at BaseLauncher.start (D:\Angular\node_modules\karma\lib\launchers\base.js:52:10)
at Object.j (D:\Angular\node_modules\karma\lib\launcher.js:108:17)
at setTimeout.bind.j (D:\Angular\node_modules\qjobs\qjobs.js:143:18) {
errno: -4094,
code: 'UNKNOWN',
syscall: 'spawn'
}
原karma.conf.js 代码如下:
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-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma'),
],
client: {
clearContext: false, // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true,
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessCI'],
customLaunchers: {
ChromeHeadlessCI: {
base: 'ChromeHeadless',
flags: [
'--headless',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-gpu',
'--disable-dev-shm-usage',
'--disable-extensions',
'--disable-infobars',
],
},
},
singleRun: false,
restartOnFileChange: true,
});
};
解法:
1、添加puppeteer
包,npm install puppeteer --save-dev
2、在karma.conf.js
添加
const puppeteer = require('puppeteer');
process.env.CHROME_BIN = puppeteer.executablePath();
具体如下: