单元测试
单个功能或接口,给定输入,得到输出。看输出是否符合预期
需要手动编写用例代码,然后统一执行
意义 :能一次性执行所有单元测试,短时间内验证所有功能是否正常
使用jest
安装 jest(npm i jest –save-dev)
创建
.test.js的文件后缀修改npm脚本
1
2
3"test": "cross-env NODE_ENV=test jest --runInBand --forceExit --colors"
// 依次执行 --runInBand
// 执行完成后退出 --forceExit
- 常用断言
1 | test("测试用户的描述",()=>{ |
- 测试http请求接口
安装supertest插件
npm i supertest --save-dev
引入app.js构建的server
1 | const request = require('supertest') |
引入server写测试用例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 const server = require('./server')
test('http test', async () => {
const response = await server.get('/json')
expect(response.body).toEqual({
title: 'koa2 json'
})
expect(response.body.title).tobe('koa2 json')
})
test('http test', async () => {
const response = await server.post('/json').send({
username:'pis',
password:321
})
})