一般我们写完代码会这样测试
function sum (a, b) {
return a + b
}
// 通过console输出值跟预期的结果对比
console.log(sum(1, 2), 3)
上线的时候会把console都删掉,但是别人使用的时候又会测一下这个功能是否正常
使用Jest测试,可以避免这样的问题出现
开始使用
安装jest和@types/jest包含的声明文件,声明文件是定义了一些类型,写代码的时候会有提示,如果你熟悉TS,大概明白这个文件了。
npm i jest @types/jest
在package里面添加一个script脚本
{
"name": "20191019",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/jest": "^24.0.19",
"jest": "^24.9.0"
}
}
默认会测试spec和test结尾的js文件
Jest默认只能测试模块,我现在把我index.js文件写的方法导出
export function sum (a, b) {
return a + b
}
qs.sepc.js中测试用例的写法
// 测试用例的写法
import { sum } from '../index'
it('测试sum函数', () => {
expect(sum(1, 2)).toBe(3)
})
然后运行代码npm run test,生成测试报告
分组describe
// 测试用例的写法
import { sum } from '../index'
// describe表示分组,分组里面一个个的用例
describe('测试基本方法', () => {
it('测试sum函数', () => {
expect(sum(1, 2)).toBe(3)
})
})
匹配器
相当,不相等,包含,等等,匹配的关系
// describe表示分组,分组里面一个个的用例
describe('测试基本方法', () => {
it('测试sum函数', () => {
expect(sum(1, 2)).toBe(3)
})
it('测试1+1=2', () => {
expect(1 + 1).toBe(2)
})
it ('对象比较', () => {
expect({name: 1}).toEqual({name: 1})
})
})
it('测试不相等', () => {
expect(1+1).not.toBe(3) // 1+1不等3
expect(3).toBeLessThan(5) // 3<5
})
it('测试包含', () => {
expect('hello').toContain('h')
expect('hello').toMatch(/h/)
})
测试DOM
it('测试删除DOM', () => {
document.body.innerHTML = `<div><button></button></div>`
let button = document.querySelector('button')
expect(button).not.toBe(null)
// 自己写的移除的DOM方法
removeNode(button);
button = document.querySelector('button')
expect(button).toBe(null)
})
测试异步
// 回调
export const getDataCallback = fn => {
setTimeout(() => {
fn({name: 'callback'})
}, 1000);
}
// promise
export const getDataPromise = fn => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({name: 'callback'})
}, 1000);
})
}
import { getDataCallback, getDataPromise } from '../index'
// 异步回调
it('测试回调函数', (done) => {
getDataCallback((data) => {
expect(data).toEqual({ name: 'callback' })
done() // 标识调用完成
})
})
it('测试promise', () => {
// 返回的promise会等待完成
return getDataPromise().then(data => {
expect(data).toEqual({ name: 'callback' })
})
})
it('测试promise', async () => {
// 使用await语法
const data = await getDataPromise()
expect(data).toEqual({ name: 'callback' })
})