一 钩子函数的作用域
每一个describe下都可以拥有自己的钩子函数,使用的钩子函数对自己的子describe的测试用例也适用。
每个子describe也可以设置自己需要的钩子函数,使用的钩子函数对自己的测试用例适用。
说明钩子函数是有作用域的,而且在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('测试增加相关的代码', () => {
beforeEach(() => {
console.log('生命周期---BeforeEach--testadd');
//实例化对象
counter = new Counter();
})
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);
});
});
});
二 单独执行某个测试用例
运用.only修饰符,它只会执行加上这个标识的测试用例,跳过其他的测试用例
test.only('测试Counter中的 addOne方法',()=>{
console.log('测试Counter中的 addOne方法');
counter.addOne();
expect(counter.number).toBe(1);
});
三 describe内的语句执行顺序
如果不是在钩子函数内的执行语句,那么会被优先执行,因此测试中需要使用的初始化数据等等最好不要放在describe中直接执行
import Counter from './Counter';
describe('Counter的测试代码', () => {
**console.log('describe 1');**
let counter = null;
//在测试之前对一些内容进入初始化,使用jest的钩子函数
beforeAll(() => {
console.log('生命周期---BeforeAll--在测试用例执行之前')
})
beforeEach(() => {
console.log('生命周期---BeforeEach--在每一个测试用例执行之前');
//实例化对象
counter = new Counter();
})
afterEach(() => {
console.log('生命周期---AfterEach--在每一个测试用例执行之后');
})
afterAll(()=> {
console.log('生命周期---AfterAll--在测试用例执行结束之后')
})
describe('测试增加相关的代码', () => {
**console.log('describe 2');**
beforeEach(() => {
console.log('生命周期---BeforeEach--testadd');
//实例化对象
counter = new Counter();
})
test.only('测试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('测试减少相关的代码', () => {
**console.log('describe 3');**
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);
});
});
});