准备条件
以第1节教程的创建的目录和代码为基础进行讲解。如果没有看过第1节教程,请关注我,查看以往该系列的文章
这节教程主要讲解在jest中的钩子函数以及钩子函数的作用域,将第1节的代码复制一份,并且把index.js
和index.test.js
文件内容全部清空
jest中有4个钩子函数
- beforeAll:所有测试之前执行
- afterAll:所有测试执行完之后
- beforeEach:每个测试实例之前执行
- afterEach:每个测试实例完成之后执行
看例子更容易理解
在 index.js
中写入一些待测试方法
export default class compute {
constructor() {
this.number = 0
}
addOne() {
this.number += 1
}
addTwo() {
this.number += 2
}
minusOne() {
this.number -= 1
}
minusTwo() {
this.number -= 2
}
}
在 index.test.js
中写测试实例
import compute from './index'
const Compute = new compute()
beforeAll(() => {
console.log('---beforeAll---')
})
afterAll(() => {
console.log('---afterAll---')
})
beforeEach(() => {
console.log('---beforeEach---')
})
afterEach(() => {
console.log('---afterEach---')
})
test('测试 addOne', () => {
Compute.addOne()
expect(Compute.number).toBe(1)
})
test('测试 minusOne', () => {
Compute.minusOne()
//这里用的同一个Computer实例,上面 +1 ,这里 -1,所以为0
expect(Compute.number).toBe(0)
})
运行一下查看结果
这里可以看到测试用例全部通过,重点是钩子函数的执行顺序
—beforeEach—和---afterEach—执行了两边,因为有两个测试实例
这里两个测试实例相互之间影响了,共用了一个compont实例,我们可以将const Compute = new compute()
放在beforEach里面就可以解决了,每次测试实例之前先重新new compute
describe
describe相当于一个块,可以将测试用例放在一个块中
修改index.test.js
中的代码
import compute from './index'
let Compute = null