Skip to main content

生命周期方法

重复性方法

这些方法会被添加到每一个测试用例的前后

  • beforeEach
  • afterEach
const { sum, sub, mul, div } = require('./tool')

beforeEach(() => {
console.log('beforeEach')
})

afterEach(() => {
console.log('afterEach')
})

test('sum', () => {
const result = sum(1, 3)
expect(result).toBe(4)
console.log('\x1b[31m%s\x1b[0m', 'test sum')
})

test('sub', () => {
const result = sub(15, 10)
expect(result).toBe(5)
console.log('\x1b[31m%s\x1b[0m', 'test sub')
})

test('mul', () => {
const result = mul(2, 3)
expect(result).toBe(6)
console.log('\x1b[31m%s\x1b[0m', 'test mul')
})

test('div', () => {
const result = div(50, 2)
expect(result).toBe(25)
console.log('\x1b[31m%s\x1b[0m', 'test div')
})

beforeEachafterEach会在每一个测试用例的前后执行。

一次性方法

在整个测试开始之前以及测试用例全部执行完之后执行的生命周期方法。

  • beforeAll
  • afterAll
// beforeAll 是在整个测试套件的第一个测试用例执行之前执行
beforeAll(()=>{
console.log("beforeAll");
})

// afterAll 会在所有测试用例执行完成之后,然后再执行 afterAll
afterAll(()=>{
console.log("afterAll");
})

分组

如果测试用例比较多,我们可以使用describe来进行分组,在一个分组里面也可以书写生命周期方法,但是在分组中的生命周期方法会变为一个局部的生命周期方法,仅对该组测试用例有效,而且还涉及到了一个顺序的问题。

const { sum, sub, mul, div } = require('./tool')

beforeAll(() => {
console.log('Global beforeAll')
})

afterAll(() => {
console.log('Global afterAll')
})

beforeEach(() => {
console.log('Global beforeEach')
})

afterEach(() => {
console.log('Global afterEach')
})

describe('group 1', () => {
beforeAll(() => {
console.log('group 1 beforeAll')
})

afterAll(() => {
console.log('group 1 afterAll')
})

beforeEach(() => {
console.log('group 1 beforeEach')
})

afterEach(() => {
console.log('group 1 afterEach')
})

test('sum', () => {
const result = sum(1, 3)
expect(result).toBe(4)
console.log('\x1b[31m%s\x1b[0m', 'test sum')
})
})
/*
Global beforeAll
group 1 beforeAll
Global beforeEach
group 1 beforeEach
test sum
group 1 afterEach
Global afterEach
group 1 afterAll
Global afterAll
*/

如果既有全局的beforeEach又有分组内部的beforeEach,那么先执行全局的beforeEach,然后再执行分组内部的beforeEach,如果是全局afterEach以及分组的afterEach,那么顺序刚好和beforeEach相反。

beforeAll是在要执行该分组的测试用例之前会执行,afterAll是在该分组所有测试用例执行完毕后执行。

test.only

test.only是用来测试特定的测试用例,也就是说,如果一个测试套件里面假设有10个测试用例,第7个测试用例书写了test.only,那么在运行整个测试套件的时候,就只会执行第 7 个测试用例。

test.only一般用于在一个测试套件中,我们要确保某一个测试用例是否通过的时候,就可以使用test.only

test.only('mul', () => {
const result = mul(2, 3)
expect(result).toBe(6)
console.log('\x1b[31m%s\x1b[0m', 'test mul')
})