Karma和Jasmine结合使用,为前端提供了单体测试框架,Karma用于执行测试用例,一般情况下它会启动浏览器然后执行测试用例,这篇文章介绍一下如何在Alpine容器中使用Karma和Jasmine执行前端测试用例与常见问题。
~ # cat /etc/alpine-release
3.9.4
~ #
使用ng test执行测试用例时,Karama会提示如下找不到Chrome浏览器的提示信息
No binary for Chrome browser on your platform. Please, set "CHROME_BIN" env variable.
缺省状态下没有Alpine容器中没有安装Chrome。
安装Alpine下的Chromium并设定CHROME_BIN
执行命令示例:
export CHROME_BIN=/usr/bin/chromium-browser && cd demo && ng test --code-coverage
使用ng test执行测试用例时,Karama会提示如下需要添加–no-sandbox选项
Cannot start Chrome
[9780:9780:1104/062415.218213:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.
执行用户为root,Karma执行时未设定no-sandbox选项。
将Karama的Headless方式以如下方式传入no-sandbox选项
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
完整的Karma的配置文件内容如下所示
/data/jenkins/workspace/angular-pipeline-job/demo # cat 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'],
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/demo'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
singleRun: true,
restartOnFileChange: true
});
};
/data/jenkins/workspace/angular-pipeline-job/demo #
https://github.com/karma-runner/karma-chrome-launcher/issues/158