基于Vue-cli3的Karma + Mocha + Chai + Vue Test Utils的前端测试框架

参考 Vue cli3 与 karma

工具简介

网上现在普遍推荐的前端测试框架为:karma + mocha + chai。由于我们使用的是Vue来构建前端项目,还可以使用Vue官方的测试工具库Vue Test Utils,可以大大减少测试代码的编写难度。

Karma

karma是测试的驱动,可以通过karma的配置文件集成测试框架, 断言库和浏览器。什么意思呢,就是通过karma可以让我们的代码在不同的浏览器中运行测试,并可以和任意主流的前端测试框架如jasmine、mocha、quint、nodeunit、nunit等集成。并且可以监听文件的变化,任意源码或者测试文件的变化都会重新运行测试。

Mocha

Mocha是JavaScript的测试框架, 浏览器和Node端均可以使用。但是Mocha本身并不提供断言的功能, 需要借助例如: Chai, 这样的断言库完成测试的功能。

关于Mocha 更多细节请参考文档

Mocha简单的示例

describe('unit', function () {
  it('example', function () {
    return true
  })
})

Mocha测试异步代码

Mocha支持Promise, Async, callback的形式

// callback
describe('异步测试Callback', function () {
  it('Done用例', function (done) {
    setTimeout(() => {
      done()
    }, 1000)
  })
})

// promise
describe('异步测试Promise', function () {
  it('Promise用例', function () {
    return new Promise((resolve, reject) => {
      resolve(true)
    })
  })
})

// async
describe('异步测试Async', function () {
  it('Async用例', async function () {
    return await Promise.resolve()
  })
})

钩子

before全部的测试用例之前执行
after全部的测试用例结束后执行
beforeEach每一个测试用例前执行
afterEach每一个测试用例后执行
describe('MochaHook', function () {
  before(function () {
    console.log('before')
  })

  after(function () {
    console.log('after')
  })

  beforeEach(function () {
    console.log('beforeEach')
  })

  afterEach(function () {
    console.log('afterEach')
  })

  it('example1', function () {
    console.log(1)
  })

  it('example2', function () {
    console.log(2)
  })
})

// before, beforeEach, 1, afterEach, beforeEach, 2, afterEach, after

skip

describe, 或者it之后添加skip。可以让Mocha忽略测试单元或者测试用例。使用skip, 测试会标记为待处理。

重试测试

设置测试失败后, 测试重试的次数

describe('retries', function () {
  it('retries', function () {
    // 设置测试的重试次数
    this.retries(3)
    const number = Math.random()
    if (number > 0.5) throw new Error()
    else return true
  })
})

slow

如果测试用例, 运行时间超过了slow设置的时间, 会被标红。

describe('unit', function () {
  it('example', function (done) {
    this.slow(100)
    setTimeout(() => {
      done()
    }, 200)
  })
})

timeout

设置测试用例的最大超时时间, 如果执行时间超过了最大超时时间,测试结果将为错误

describe('unit', function () {
  it('example', function (done) {
    this.timeout(100)
    setTimeout(() => {
      done()
    }, 200)
  })
})
Chai

Chai是断言库。

Chai的详细用法请参见官网

Vue Test Utils

Vue的官方的单元测试框架,它提供了一系列非常方便的工具,使我们可以更轻松地为Vue应用编写单元测试。

Vue Test Utils的详细用法请参见官网

构建单元测试项

使用cli3构建项目

使用Vue-cli3构建项目,在构建时注意需要选中单元测试,测试类型选择mocha + chai。等待项目构建完成。

集成karma

安装Karma的依赖包

cnpm install --save karma karma-chrome-launcher karma-mocha karma-sourcemap-loader karma-spec-reporter karma-webpack

在项目的根目录执行karma的初始化方法,生成karma.config.js

karma init

初始化过程中,会有一些选项,用于生成配置文件的默认值。

Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> mocha

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

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.
>

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

更改生成的karma.config.js文件。

// Karma configuration
// Generated on Mon Jan 28 2019 16:15:39 GMT+0800 (中国标准时间)

let webpackConfig = require('@vue/cli-service/webpack.config.js')

module.exports = function (config) {
  config.set({
    webpack: webpackConfig,
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

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

    // list of files / patterns to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      '**/*.spec.js': ['webpack', 'sourcemap']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // 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,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeHeadless'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}

添加了webpack相关的配置,增加了测试文件需要预编辑的文件的匹配条件式。

编写测试用例

理论上应为每个Vue组件分别写一个单元测试文件。测试文件名应该为“[组件名].spec.js”,比如组件名为HelloWorld.vue,那么对应的测试文件名为HelloWorld.spec.js

运行测试用例

package.json中添加一条script。

"test": "karma start"

然后运行执行命令,开始测试。

npm run test

问题

使用Vue-cli3自动搭建的测试环境,没有集成karma直接运行开始测试,webpack的编译报错

tests/unit/pre-setup.js

// from @vue/cli-plugin-unit-mocha/setup.js
require('jsdom-global')(undefined, { pretendToBeVisual: true, url: 'http://localhost' })

// https://github.com/vuejs/vue-test-utils/issues/936
// better fix for "TypeError: Super expression must either be null or
// a function" than pinning an old version of prettier.
window.Date = Date

package.json

"scripts": {
  "test": "vue-cli-service test:unit --require tests/unit/pre-setup.js"
}

集成karma后,没有这个问题。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值