学习 Jest - Setup and Teardown
Setup and Teardown
直接翻译过来就是安装和拆卸。
通常编写测试时需要预先进行一些配置工作,并在测试后进行相关整理,Jest 提供了相关帮助函数
重复设置
假设需要重复做很多测试,可使用 beforeEach
和 afterEach
钩子
// beforeEach 和 afterEach
// 可以测试异步代码
beforeEach(() => {
// before do somethings...
})
afterEach(() => {
// after do somethings...
})
test('testing', () => {
expect('testings...')
})
单次设置
某些情况下,只需进行一次设置即可
// 若返回 Promise 且可重用
// 可更改为此
beforeAll(() => {
return AsyncInitData()
})
afterAll(() => {
return AsyncCloseData()
})
test('testing', () => {
expect('testings...')
})
范围
// 应用于所有测试
beforeEach(() => {
return AsyncInitData()
})
test('init', () => {
expect('a').toBe('a')
})
describe('other testing', () => {
// 只在当前块内
beforeEach(() => {
return AsyncInitDataTwo()
})
test('other test', () => {
expect('a').toBe('a')
})
})
执行顺序
Jest 在执行任何实际测试前,会先执行所有 describe 块
这是 setup 和 teardown 要在 before 和 after 处理程序中而不是在 describe 块的一个原因
一旦 describe 块完成, Jest 会按照收集阶段遇到的顺序连续运行所有测试,等待每个测试完成并整理好后继续
beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
beforeAll(() => console.log('2 - beforeAll'));
afterAll(() => console.log('2 - afterAll'));
beforeEach(() => console.log('2 - beforeEach'));
afterEach(() => console.log('2 - afterEach'));
test('', () => console.log('2 - test'));
});
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
describe('describe outer', () => {
console.log('describe outer-a');
describe('describe inner 1', () => {
console.log('describe inner 1');
test('test 1', () => console.log('test 1'));
});
console.log('describe outer-b');
test('test 2', () => console.log('test 2'));
describe('describe inner 2', () => {
console.log('describe inner 2');
test('test 3', () => console.log('test 3'));
});
console.log('describe outer-c');
});
// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test 1
// test 2
// test 3
学习 Jest - Setup and Teardown
http://localhost:8080/archives/1813f257-cdaf-47e9-a7c4-c47a7b6e53ba