(九) 单元测试环境配置
http://karma-runner.github.io/
# 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
// 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
},
autoWatch: true, // 启用或禁用自动检测文件变化进行测试
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
]
})
}
"scripts": {
"test:ui": "karma start",
},
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)
})
})
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')
})
})
image.png
image.png