ในการทดสอบ มักจะมีการทำงานบางอย่างที่ทำซ้ำๆ ไม่ว่าจะเป็นการเตรียมข้อมูลใหม่ การ clear ข้อมูล หากมีการทำงานซ้ำๆ เราสามารถใช้การ setup และ teardown ได้ โดยสามารถใช้งานได้ดังนี้
Repeating Setup
หากเรามีงานที่ต้องทำซ้ำๆ สำหรับการทดสอบหลายๆ ครั้ง เราสามารถใช้ beforeEach
และ afterEach
hooks ได้
beforeEach(() => {
console.log('to do before test')
})
afterEach(() => {
console.log('to do after test')
})
test('add 1 + 2 to equal 3', () => {
expect(1 + 2).toEqual(3)
})
test('add 3 + 4 to equal 7', () => {
expect(3 + 4).toEqual(7)
})
beforeEach & afterEach
One-Time Setup
ถ้าหากเราต้องการตั้งค่าเพียงครั้งเดียวของการทดสอบในไฟล์ๆ นั้น ให้ใช้ beforeAll
และ afterAll
เพื่อจัดการกับสถานการณ์นี้
beforeAll(() => {
console.log('to do before all test')
})
afterAll(() => {
console.log('to do after all test')
})
test('add 1 + 2 to equal 3', () => {
expect(1 + 2).toEqual(3)
})
test('add 3 + 4 to equal 7', () => {
expect(3 + 4).toEqual(7)
})
beforeAll & afterAll
Scope
การใช้งาน คำสั่งเหล่านี้ ก็มี scope ของมันอยู่เหมือนกัน หากเราประกาศไว้ข้างนอก จะสามารถใช้งานได้ทั้งหมดกับทุกการทดสอบในไฟล์ๆ นั้น
หากเราประกาศไว้ภายใน describe
ก็เป็นการกำหนดการใช้งานภายใน scope ของ describe
นั้น
// Applies to all tests in this file
beforeEach(() => {
console.log('to do before test')
})
// Test case
test('add 1 + 2 to equal 3', () => {
expect(1 + 2).toEqual(3)
})
describe('matching cities to foods', () => {
// Applies only to tests in this describe block
beforeEach(() => {
console.log('to do before test in describe')
})
// Test case
test('add 3 + 4 to equal 7', () => {
expect(3 + 4).toEqual(7)
})
})
Scope of setup & teardown
ลำดับในการ execution ของ hooks ทั้งหมด
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'))
})
// Output
// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
execution of all hooks