前端单元测试-karma+mocha+chai

一、概念普及

        1、单元测试运行环境:

                运行环境是集成一系列功能的工具,我们可以通过它来选择“测试框架”、自动打开浏览器、查看测试结果等功能。我们可以把它近似的理解为vue的vue-cli。

                我们选用karma作为运行环境

        2、单元测试框架:

                测试框架规定了测试用例的代码结构和测试流程。我们可以近似理解为类似vue的概念。

                我们选用mocha作为测试框架

        3、断言库:

                断言是编程术语,表示为一些布尔表达。

                断言库是对预期值或者效果进行判断的工具,我们会在测试框架的结构中填充我们对当前测试用例的预期值的断言,从而根据预期值的真假来判断测试是否通过。

                我们选用chai作为断言库

二、karma安装和配置

        1、安装运行环境karma

                1、创建项目test-demo,并进入test-demo目录。

                2、在项目目录中打开命令行工具。

                3、安装

                

npm i karma

                4、运行

node_modules/.bin/karma start

        2、配置简化运行方式:

                a、配置package.json

  "scripts": {
    "test": "./node_modules/.bin/karma start"
  },

                      运行命令

npm test

                b、为了方便也可以全局安装(不用全局安装也可以)

yarn global add karma-cli

                      运行命令

karma start

                       因为命令已经很短了所以可以不配置package.json,如果配也可以。

  "scripts": {
    "test": "karma start"
  },

        3、配置使用karma

                安装好karma之后,我们开启配置向导:

                本地安装的运行

./node_modules/.bin/karma init

                全局安装的运行

karma init
或
./node_modules/.bin/karma init

                接下来在配置向导中进行配置,切换选项可以使用tab键。

karma init
# 选择测试框架,这里我选择mocha
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> mocha

# 是否引入Require.js,需要
Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no

# 选择使用的浏览器,可以使用无头浏览器PhantomJS,不过需要单独安装PhantomJS
# 这里也可以选择多个浏览器,测试用例将在多个浏览器里执行
# 这里我只选择了Chrome
Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
>

# 告诉需要执行的测试用例的代码路径,支持正则
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
> test/*.js
10 05 2017 15:00:08.723:WARN [init]: There is no file matching this pattern.

>

# 上面指定的路径中需要排除在外的文件
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>

# 是否观察文件的变化
Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes


Config file generated at "/Users/linliang/Src/frontend/karma-intro/karma.conf.js".

                配置完成后package.json文件中多了一些相关karma的依赖,项目目录下生成karma.conf.js文件,他是karma的配置文件。

         4、编写第一个测试用例验证一下

                项目根目录中创建test/index.js,功能就是输出一个字符串,来验证一下测试用例能不能跑起来。

// test/index.js 目前路径不能改变。我们初始化时候配置好的,以后也可以在配置文件中修改。
/*
files: [
  'test/*.js'
],
*/
describe ('a test', function () {
  it('pring hello karma', function() {
    console.log('hello karma')
  })
})

                运行npm test

                 并且会自动打开浏览器,我们点击浏览器右侧的debug,然后打开控制台,看到测试用例输出内容。

                 上面图中已经看到我们输出结果 hello karma。

        5、命令行运行测试用例

                package.json中配置

  "scripts": {
    "testcmd": "./node_modules/.bin/karma run"
  },

                项目根目录下新打开一个命令行工具,运行npm run testcmd。

        6、运行指定的测试用例

               整个项目中的测试用例已经很多了,默认情况下是把所有的测试用例都执行一遍,但是有的时候我们只想执行某个测试用例。

// 表示只运行匹配特定字符串a test的测试用例
npm run testcmd -- --grep 'a test'

        7、ES6语法转换

                在不支持ES6的环境下,想要使用ES6语法,我们就需要进行转换了。

npm i karma-babel-preprocessor babel-preset-env

                创建.babelrc,配置babel的预转换格式

{
  "presets": ["env"]
}

               修改karma.conf.js,编辑preprocessors部分,让所有的js文件都先用babel转换一下。

preprocessors: {
    "test/*.js": ['babel']
},

        8、配合webpack使用第三方模块和使用(istanbul生成覆盖率html文档)

依赖:

    "babel-core": "^6.26.3",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-plugin-transform-vue-jsx": "^3.7.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-2": "^6.24.1",
    "babel-plugin-syntax-jsx": "^6.18.0",
    "core-js": "^3.6.5",
    "extract-text-webpack-plugin": "^3.0.2",
    "karma-babel-preprocessor": "^8.0.1",
    "chai": "^4.2.0",
    "cross-env": "^5.2.0",
    "karma": "^4.0.1",
    "karma-chai": "^0.1.0",
    "karma-coverage": "^1.1.2",
    "karma-spec-reporter": "0.0.32",
    "karma-webpack": "^2.0.2",
    "mocha": "^6.0.2",
    "webpack": "^3.6.0",
    "babel-plugin-istanbul": "^4.1.1",
    "babel-loader": "^8.2.2",
    "babel-preset-es2015": "^6.24.1",
    "karma-chrome-launcher": "^3.1.0",
    "karma-mocha": "^2.0.1",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "typescript": "~4.1.5",
    "vue-template-compiler": "^2.6.11"

karma.conf.js:

// Karma configuration
// Generated on Wed Aug 04 2021 22:37:11 GMT+0800 (中国标准时间)
var webpackConfig = require('./webpack.test.config');
module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // 告诉karma用的测试框架(mocha)和断言库 (karma-chai)
    // frameworks to use
    // available frameworks: https://www.npmjs.com/search?q=keywords:karma-adapter
    frameworks: ['mocha', 'chai'],

    // 测试时忽略打包信息
    webpackMiddleware: {
      noInfo: true
    },

    // 生成的覆盖率报告 配置项
    // coverageReporter: {
    //   type : 'html',
    //   dir : 'coverage/'
    // }
    coverageReporter: {
      dir: './coverage',
      reporters: [
        { type: 'lcov', subdir: '.' },
        { type: 'text-summary' } //在控制台输出摘要
      ]
    },

    // list of files / patterns to load in the browser
    files: [
      'test/*.js'
    ],

    // 排除文件,可以是正则
    // list of files / patterns to exclude
    exclude:["karma.conf.js", "webpack.test.config.js"],

    //对指定文件的预处理
    // preprocess matching files before serving them to the browser
    // available preprocessors: https://www.npmjs.com/search?q=keywords:karma-preprocessor
    preprocessors: {
        "test/unit/*.js": ['babel', 'webpack']
    },

    // 测试报告的显示格式(命令行内的显示格式)  karma-mocha-reporter
    // 测试覆盖率报告  karma-coverage
    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://www.npmjs.com/search?q=keywords:karma-reporter
    // reporters: ['progress'],
    reporters: ['spec', 'coverage'],

    //colors 报表中是否有颜色区分
    colors:true,


    // web server port
    port: 9876,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // 检测文件变动 文件变动自动执行测试文件
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // 自动启用Chrome浏览器执行代码 karma-chrome-launcher
    // start these browsers
    // available browser launchers: https://www.npmjs.com/search?q=keywords:karma-launcher
    browsers: ['Chrome'],

    //是否依附浏览器运行
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    //并发数,同时支持多少个浏览器运行
    // Concurrency level
    // how many browser instances should be started simultaneously
    concurrency: Infinity,
    // 读取webpack配置并启动
    webpack: webpackConfig,
  })
}

.babelrc:

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": ["transform-vue-jsx", "transform-runtime"],
  "env": {
    "test": {
      "presets": ["env", "stage-2"],
      "plugins": ["transform-vue-jsx", "istanbul"]  
    }
  }
}

webpack.test.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

修改package.json

"scripts": {
    "test": "cross-env BABEL_ENV=test karma start test/karma.conf.js"
  }

三、测试框架mocha说明

        1、我们在karma init 的时候已经配置了我们的测试框架是moucha,所以不需要在安装就可以直接使用了。

        2、describe描述 、it断言 属于mocha框架中的语法,包含其他语法和钩子函数可以参与官网:https://mochajs.cn/

四、断言库chai说明

        1、安装

npm install chai

        2、使用

import {expect} from 'chai'
var expect = chai.expect; 

describe ('a test', function () {
  it('1===1',function(){
    // 调用相关代码及设置断言
    expect(1).to.equal(1);
  })
})

        3、运行单元测试

npm run testcmd

        4、断言库chai的用法可参考官网:https://www.chaijs.com/

总结:以上使用 karma+mocha+chai 实现前端单元测试的环境已经搭建好了。mocha和chai还有覆盖率问题后续深入研究。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值