Jenkins基础:使用NPM构建前端应用8:使用Karma和Jasmine进行前端测试

在前面的文章中我们介绍了如何集成SonarQube来实现前端应用的代码质量状况的显示,在这篇文章中将继续介绍如何将Karma、Jasmine的前端测试集成到Jenkins的流水线中。

事前准备

SonarQube环境

构建SonarQube环境,可参看如下内容:

  • https://liumiaocn.blog.csdn.net/article/details/56673905

注:此节开始的示例SonarQube版本开始使用LTS 7.9.1,服务端口为9001

Dockerfile

~ # cat /tmp/Dockerfile 
FROM nginx:latest

ADD demo/dist/* /usr/share/nginx/html
~ # 

Karma配置文件

将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 # 

安装Chromium,可参看:

  • https://blog.csdn.net/liumiaocn/article/details/102903761

基础知识

如果对于NodeJS的插件使用或者在Jenkins的Jenkinsfile中使用npm的基本方法不熟悉的开发者可以先行查看如下文章。

Jenkinsfile

node {
   stage('Prepare Node and NPM') { // confirm nodejs plugin and setting
    env.NODEJS_HOME = "${tool 'nodejs-10.15.3'}"
	env.PATH="${env.NODEJS_HOME}/bin:${env.PATH}"
	sh 'npm --version'
   }
   stage('Prepare Angular CLI') { // install global angular cli
    sh 'npm -g install @angular/cli'
    sh 'ng --version'
   }
   stage('Prepare Angular Project') { // prepare angular demo app
    sh 'if [ ! -d demo ]; then ng new demo --style less; fi'
   }
   stage('Build Angular Project') { // build angular demo app
    sh 'cd demo && npm install && npm run build'
   }
   stage('Build Angular demo image') { // build image and push to registry
    sh 'cp /tmp/Dockerfile .'
    docker.withRegistry('http://192.168.31.242:5000') {
      def angular_img = docker.build("angulardemo:${env.BUILD_ID}")
      angular_img.push()
    }
   }
   stage('Deploy Angular image') { // docker run angular image
    docker.image("angulardemo:${env.BUILD_ID}").run('-p 8888:80')
   }
   stage('Jasmine Unit Test') { // Unit Test
    sh 'export CHROME_BIN=/usr/bin/chromium-browser && cd demo && ng test --code-coverage'
   }
   stage('Sonar-Scanner Angular Demo App') { // sonar-scanner
    sh 'cd demo && /usr/local/share/sonar/bin/sonar-scanner -Dsonar.projectKey=demo -Dsonar.sources=src -Dsonar.host.url=http://192.168.31.242:9001 -Dsonar.login=admin -Dsonar.password=admin'
   }
}

代码说明:
angular是通过cli来创建应用程序脚手架的,在Prepare Angular Project的stage中通过使用ng new demo创建了demo的angular应用。而在后续的stage中则通过npm install安装相关的依赖,通过npm run build则生成了结果的dist目录与文件,然后通过docker.withRegistry设定私库地址,通过docker.build构建,通过push方法进行推送,然后使用image的run方法运行容器,通过ng test执行测试用例并生成lcov的测试率覆盖文件,而通过内置的sonar-scanner来进行代码的质量扫描。

结果确认

  • 执行日志确认
    执行日志如下所示:
Started by user root
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /data/jenkins/workspace/angular-pipeline-job
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Prepare Node and NPM)
[Pipeline] tool
[Pipeline] sh
+ npm --version
6.4.1
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Prepare Angular CLI)
[Pipeline] sh
+ npm -g install @angular/cli
...省略
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Jasmine Unit Test) (hide)
[Pipeline] sh
+ export 'CHROME_BIN=/usr/bin/chromium-browser'
+ cd demo
+ ng test --code-coverage
Your global Angular CLI version (8.3.17) is greater than your local
version (8.3.12). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".
[32m04 11 2019 20:53:24.681:INFO [karma-server]: [39mKarma v4.1.0 server started at http://0.0.0.0:9876/
[32m04 11 2019 20:53:24.687:INFO [launcher]: [39mLaunching browsers ChromeHeadlessNoSandbox with concurrency unlimited
[32m04 11 2019 20:53:24.719:INFO [launcher]: [39mStarting browser ChromeHeadless
[32m04 11 2019 20:53:30.866:INFO [HeadlessChrome 72.0.3626 (Linux 0.0.0)]: [39mConnected on socket Tj7--y2Da5ef4IaZAAAA with id 15771968
HeadlessChrome 72.0.3626 (Linux 0.0.0): Executed 0 of 3 SUCCESS (0 secs / 0 secs)
[1A[2KHeadlessChrome 72.0.3626 (Linux 0.0.0): Executed 1 of 3 SUCCESS (0 secs / 0.481 secs)
[1A[2KHeadlessChrome 72.0.3626 (Linux 0.0.0): Executed 2 of 3 SUCCESS (0 secs / 0.66 secs)
[1A[2KHeadlessChrome 72.0.3626 (Linux 0.0.0): Executed 3 of 3 SUCCESS (0 secs / 0.774 secs)
[1A[2KHeadlessChrome 72.0.3626 (Linux 0.0.0): Executed 3 of 3 SUCCESS (0.92 secs / 0.774 secs)
TOTAL: 3 SUCCESS
TOTAL: 3 SUCCESS
TOTAL: 3 SUCCESS
=============================== Coverage summary ===============================
Statements   : 100% ( 6/6 )
Branches     : 100% ( 0/0 )
Functions    : 100% ( 1/1 )
Lines        : 100% ( 5/5 )
================================================================================
[Pipeline] }
...省略
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
  • 构建结果
    在blueocean上也能实时地确认到构建的输出信息
    在这里插入图片描述

  • 登陆SonarQube确认扫描结果
    在这里插入图片描述
    在这里插入图片描述
    需要注意的是此处的覆盖率还没有正确显示出来,在接下来的文章中将继续展开。

淼叔 CSDN认证博客专家 神经网络 TensorFlow NLP
资深架构师,PMP、OCP、CSM、HPE University讲师,EXIN DevOps Professional与DevOps Master认证讲师,曾担任HPE GD China DevOps & Agile Leader,帮助企业级客户提供DevOps咨询培训以及实施指导。熟悉通信和金融领域,有超过十年金融外汇行业的架构设计、开发、维护经验,在十几年的IT从业生涯中拥有了软件开发设计领域接近全生命周期的经验和知识积累,著有企业级DevOps技术与工具实战。
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页