本篇我们主要通过自己编写一些测试代码来了解一下单元测试原理和过程。
一、项目目录

二、代码演练
1、编写要测试的数学函数库(math.js)
function add(a, b){
return a + b
}
function sub(a, b){
return a - b
}
function multi(a, b){
return a - b
}
module.exports = {
add, sub, multi
}
2、编写测试代码(math.test.js)
const { add, sub, multi } = require('./math')
{
let result = add(1,1)
let expected = 2
if(result !== expected){
throw new Error(`1+1 expected ${expected},but is ${result}`)
} else {
console.log('pass...')
}
}
{
let result = sub(2,1)
let expected = 1
if(result !== expected){
throw new Error(`2-1 expected ${expected}, but is ${result}`)
} else {
console.log('pass ...')
}
}
{
let result = multi(2,2)
let expected = 4
if(result !== expected){
throw new Error(`2 * 2 expected ${expected},but is ${result}`)
} else {
console.log('pass ...')
}
}
node math.test.js之后的结果如下图所示:

从报错的结果,我们就可以知道math库中的multi方法出错,所以我们进行相应的修改即可。
三、封装我们自己的测试库
前面的代码中,我们已经实现了测试的相关逻辑,这就是单元测试底层的实现逻辑,我们可以将上面的代码简单封装一下,实现更完善的功能。
const { add, sub, multi } = require('./math')
function expect(result){
return {
toBe: function(actual){
if(result !==actual){
throw new Error(`预期值和实际值不相等,预期${actual} 结果是${result}`)
}
}
}
}
function test(desc, fn){
try {
fn()
console.log(`${desc} 测试通过`)
} catch (error) {
console.log(`${desc} 没有通过测试,${error}`)
}
}
test('测试加法3+7',() => {
expect(add(3,7)).toBe(10)
})
test('测试减法2-1',() => {
expect(sub(2,1)).toBe(1)
})
test('测试乘法 2 * 2',() => {
expect(multi(3,3)).toBe(9)
})
node math.test.js 运行结果如下:

是不是很有jest的感觉呀,那就对了,走你~~~~
网友评论