Jest中的钩子函数相当于生命周期函数,在执行测试用例时,有先后调用的顺序。
一 Jest常用的钩子函数
beforeAll 在测试用例执行之前运行
beforeEach 在每一个测试用例执行之前运行
afterAll 在测试用例执行结束之后运行
afterEach 在每一个测试用例执行之后运行
import Counter from './Counter';
let counter = null;
//在测试之前对一些内容进入初始化,使用jest的钩子函数
beforeAll(() => {
console.log('生命周期---BeforeAll--在测试用例执行之前')
})
beforeEach(() => {
console.log('生命周期---BeforeEach--在每一个测试用例执行之前');
//实例化对象
counter = new Counter();
})
afterEach(() => {
console.log('生命周期---AfterEach--在每一个测试用例执行之后');
})
afterAll(()=> {
console.log('生命周期---AfterAll--在测试用例执行结束之后')
})
test('测试Counter中的 addOne方法',()=>{
console.log('测试Counter中的 addOne方法');
counter.addOne();
expect(counter.number).toBe(1);
});
test('测试Counter中的 addTwo方法',()=>{
console.log('测试Counter中的 addTwo方法');
counter.addTwo();
expect(counter.number).toBe(2);
});
test('测试Counter中的 minusOne方法',()=>{
console.log('测试Counter中的 minusOne方法');
counter.minusOne();
expect(counter.number).toBe(-1);
});
test('测试Counter中的 minusTwo方法',()=>{
console.log('测试Counter中的 minusTwo方法');
counter.minusTwo();
expect(counter.number).toBe(-2);
});
二 对测试用例进行分组
与mocha的语法相似,运用describe语法,第一个参数编写测试用例的名字,第二个参数编写需要执行的测试用例。
import Counter from './Counter';
describe('Counter的测试代码', () => {
let counter = null;
//在测试之前对一些内容进入初始化,使用jest的钩子函数
beforeAll(() => {
console.log('生命周期---BeforeAll--在测试用例执行之前')
})
beforeEach(() => {
console.log('生命周期---BeforeEach--在每一个测试用例执行之前');
//实例化对象
counter = new Counter();
})
afterEach(() => {
console.log('生命周期---AfterEach--在每一个测试用例执行之后');
})
afterAll(()=> {
console.log('生命周期---AfterAll--在测试用例执行结束之后')
})
describe('测试增加相关的代码', () => {
test('测试Counter中的 addOne方法',()=>{
console.log('测试Counter中的 addOne方法');
counter.addOne();
expect(counter.number).toBe(1);
});
test('测试Counter中的 addTwo方法',()=>{
console.log('测试Counter中的 addTwo方法');
counter.addTwo();
expect(counter.number).toBe(2);
});
});
describe('测试减少相关的代码', () => {
test('测试Counter中的 minusOne方法',()=>{
console.log('测试Counter中的 minusOne方法');
counter.minusOne();
expect(counter.number).toBe(-1);
});
test('测试Counter中的 minusTwo方法',()=>{
console.log('测试Counter中的 minusTwo方法');
counter.minusTwo();
expect(counter.number).toBe(-2);
});
});
});