【xingorg1-ui】基于vue3.0从0-1搭建组件库 (九) 单元测试配置

(九) 单元测试环境配置

karma:进行浏览器UI测试

http://karma-runner.github.io/

1、依赖安装

# Install Karma && Install plugins that your project needs:
$ npm install -D karma karma-chrome-launcher karma-mocha karma-sourcemap-loader karma-spec-reporter karma-webpack karma-chai mocha
image.png
image.png

2、karma.conf.js配置文件

// karma.conf.js http://karma-runner.github.io/
const webpackConfig = require('@vue/cli-service/webpack.config')

module.exports = function(config{
  config.set({
    frameworks: ['mocha'], // 测试框架列表,可用的框架:https://npmjs.org/browse/keyword/karma-adapter
    files: ['tests/**/*.spec.js'], // 被测试文件列表,测试文件tests下的所有spec.js文件
    preprocessors: { // 预处理器:允许您在文件被提供给浏览器之前对其进行处理
      '**/*.spec.js': ['webpack''sourcemap'//  // 可用的预处理: https://npmjs.org/browse/keyword/karma-preprocessor
    },
    autoWatchtrue// 启用或禁用自动检测文件变化进行测试
    webpack: webpackConfig,
    reporters: ['spec'], // 使用测试结果报告者(https://npmjs.org/browse/keyword/karma-reporter)单测、覆盖率coverage报告
    browsers: [ // 测试启动的浏览器, 可用的浏览器 http://karma-runner.github.io/5.2/config/browsers.html
      'ChromeHeadless' // 无头浏览器,不会展示出来。其他参数如'Chrome'。可用的浏览器:https://www.npmjs.com/search?q=keywords:karma-launcher
    ]
  })
}

3、package.json脚本配置

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

4、单测用例

demo

utils>example.spec.js

import { expect } from 'chai' // jest中的断言库
// import { shallowMount } from '@vue/test-utils' // 当前包目前不兼容vue3

describe('测试用例', () => {
  it('1+1=3吗', () => {
    expect(1+1).to.eq(2)
  })
})

断言库 - chai

https://www.chaijs.com/

手写用例-button.spec.js(有报错,再研究吧)

import { expect } from 'chai'
import GjfButton from 'packages/button'
// import {createApp} from 'vue' // '[Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".'
import { createApp } from 'vue/dist/vue.esm-bundler.js' // 上边的代码,组件提供了template选项,但是运行时不支持,需要引入vue/dist/vue.esm-bundler.js这个文件才能渲染template
describe('button按钮测试用例', () => {
  it('是不是button按钮啊?', () => {
    /* 
    const contianer = document.createElement('div')
    const app = createApp({
      template: `<gjf-button />`,
      components: {
        'gjf-button': GjfButton
      }
    })
    app.mount(contianer)
    let html = app.$el.innerHTML // TypeError: Cannot read property 'innerHTML' of undefined 
    expect(html).to.eq('button')
    */

    const container = document.createElement('div')
    const app = createApp({
      template`<gjfButton />`,
      components: {
        'gjfButton': GjfButton
      }
    }).mount(container)
    console.log(app, 111, app.$el)
    let html = app.$el
    expect(html).to.match('button')
  })
})

5、测试执行

测试通过

image.png
image.png

测试失败:

image.png
image.png
posted @ 2020-11-17 00:06  xing.org1^  阅读(359)  评论(0编辑  收藏  举报