前言

有没有发现一个大项目 一般都有一个test的文件夹 都是用来测试写的代码 比如常用的vue 框架

image-20220824101009987

测试下的文件夹

Karma

创建项目

//可以手动创建 可以linux命令创建
mkdir testprject
//进入项目
cd testprject
//初始化项目
npm init -y

创建测试文件夹

在项目下创建 unite2e这两个文件夹

image-20220824102900497

unit文件夹下面创建 index.jsindex.spec.js 测试的文件夹都是*.spec.js 被测试的文件都是普通的js

image-20220824103103524

Index.js

//测试这个方法
window.add=function (a){
return a+1;
}

index.spec.js

describe('测试基本函数的API',function(){
it('+1测试应用', function () {
//断言库 //toBe(结果)
expect(window.add(1)).toBe(2);
});
});

安装配置karma

//下载karma
npm i karma

修改package.json 执行初始化

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
//karma 初始化
"karma init": "karma init",
//karma 运行
"karma:start": "karma start"
}

iShot_2022-08-24_09.42.40

初始化之后会生成一个配置文件karma.conf.js

//下载包
npm i jasmine-core
npm i karma-jasmine
npm i phantomjs karma-phantomjs-launcher -D
npm i karma-chrome-launcher

修改karma.conf.js配置文件

// list of files / patterns to load in the browser
//添加测试文件 和 被 测试文件
files: [
'./unit/**/*.js',
'./unit/**/*.spec.js'
],

// start these browsers
// available browser launchers: https://www.npmjs.com/search?q=keywords:karma-launcher
browsers: ['Chrome']

//不打开浏览器 在窗口执行 默认为false
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,

运行

npm run karma:start

成功

image-20220824115210238

错误

image-20220824115250323

报表

显示代码的执行的覆盖率

image-20220824121356445

修改index.js

window.add=function (a){
if(a===1){
return 1;
}else{
return a+1;
}
return a+1;
}

下载包

参考karma-coverage

npm i karma-coverage

在目录下面创建一个docs文件

image-20220824122352846

修改karma.conf.js配置文件

preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'unit/**/*.js': ['coverage']
},

// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://www.npmjs.com/search?q=keywords:karma-reporter
reporters: ['progress', 'coverage'],

//输出路径
coverageReporter: {
type : 'html',
dir : 'docs/coverage/'
}

Jest

参考 Jest

安装

npm install --save-dev jest

配置package.json

"scripts": {
"jest:test": "jest"
}

src下面创建sum.js

function sum(a, b) {
return a + b;
}
module.exports = sum;

unit下面创建 sum.spec.js

const sum = require('../src/sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(2, 2)).toBe(3);
});

错误

image-20220824135614918