测试

webpack vue-cli模板为你提供预配置的单元测试和e2e测试设置。

当测试*.vue文件时,我们不能使用普通的基于CommonJS的测试运行器,因为它不知道如何处理*.vue文件。相反,我们仍然使用Webpack + vue-loader来打包我们的测试文件。建议的设置是使用Karmakarma-webpack

Karma是一个测试运行器,启动浏览器并为您运行测试。您可以选择要测试的浏览器以及要使用的测试框架(例如Mocha或Jasmine)。下面是一个使用Jasmine测试框架在PhantomJS中运行测试的Karma配置示例:

  1. npm install\
  2. karma karma-webpack\
  3. karma-jasmine jasmine-core\
  4. karma-phantomjs-launcher phantomjs\
  5. --save-dev
  1. //我们只需要使用完全相同的webpack配置
  2. //但是,请记住删除原始条目,因为我们在测试期间不需要它
  3. var webpackConfig = require('./webpack.config.js')
  4. delete webpackConfig.entry
  5. // karma.conf.js
  6. module.exports = function (config) {
  7. config.set({
  8. browsers: ['PhantomJS'],
  9. frameworks: ['jasmine'],
  10. // 这是我们所有测试文件的入口
  11. files: ['test/index.js'],
  12. // 我们将把入口文件传递给webpack进行打包。
  13. preprocessors: {
  14. 'test/index.js': ['webpack']
  15. },
  16. // 使用webpack配置
  17. webpack: webpackConfig,
  18. // 删除没用得文本
  19. webpackMiddleware: {
  20. noInfo: true
  21. },
  22. singleRun: true
  23. })
  24. }

test/index.js入口文件中添加:

  1. // test/index.js
  2. // 要求所有测试文件使用特殊的Webpack功能
  3. // https://webpack.github.io/docs/context.html#require-context
  4. var testsContext = require.context('.', true, /\.spec$/)
  5. testsContext.keys().forEach(testsContext)

这个入口文件只简单的require同一文件夹.spec.js结尾的所有其他文件。现在我们可以写一些测试:

  1. // test/component-a.spec.js
  2. var Vue = require('vue')
  3. var ComponentA = require('../../src/components/a.vue')
  4. describe('a.vue', function () {
  5. // 断言 JavaScript 条件
  6. it('should have correct message', function () {
  7. expect(ComponentA.data().msg).toBe('Hello from Component A!')
  8. })
  9. // 通过实际渲染该组件来断言渲染结果
  10. it('should render correct message', function () {
  11. var vm = new Vue({
  12. template: '<div><test></test></div>',
  13. components: {
  14. 'test': ComponentA
  15. }
  16. }).$mount()
  17. expect(vm.$el.querySelector('h2.red').textContent).toBe('Hello from Component A!')
  18. })
  19. })

要运行测试,需要添加如下的NPM脚本:

  1. // package.json
  2. ...
  3. "scripts": {
  4. ...
  5. "test": "karma start karma.conf.js"
  6. }
  7. ...

Finally, run:

  1. npm test

重申一遍,webpack vue-cli模板包含一个关于测试的完整工作示例。