Jest - Setup and Teardown (beforeEach, afterEach, beforeAll, afterAll)

REASON·2022년 11월 11일
0

STUDY

목록 보기
114/127

자바스크립트 테스트 프레임워크 Jest

테스트 코드가 실행 전에 작업할 것이 있다면 beforeEach, beforeAll을 사용할 수 있고
테스트 코드 실행 후에 작업할 것이 있다면 afterEach, afterAll을 사용할 수 있다.

beforeEach

테스트가 수행되기 전에 무언가 동작 시키고 싶은 경우 beforeEach를 사용하면 된다.

beforeEach(() => {
  // 테스트 코드 수행 전에 실행하고 싶은 코드 작성
});

afterEach

테스트 이후 수행하고 싶은 것이 있다면 afterEach에 작성해주면 된다.

afterEach(() => {
  // 테스트 코드 수행 후에 실행하고 싶은 코드 작성
});

beforeEach와 afterEach 외에도 beforeAll과 afterAll이 있다.

파일 시작과 끝 1회씩만 수행하고 싶다면 beforeAll과 afterAll을 사용해볼 수 있을 것이다.

beforeAll

테스트 코드가 여러개가 있는 경우 모든 테스트가 실행되기 전에 1회 실행된다.
beforeEach는 테스트 코드 마다 실행 전에 수행됐다면 beforeAll은 모든 테스트가 실행되기 전 최초 1회 실행된다고 볼 수 있다.

afterAll

모든 테스트가 끝난 다음에 실행된다.
afterBefore는 테스트가 여러개 인 경우 하나의 테스트가 끝날 때마다 실행되지만 afterAll은 모든 테스트가 종료되고 마지막에 1회 수행된다.

실행 순서 :
beforeAll -> beforeEach -> afterEach -> afterAll로 동작한다.

describe 내부에 작성하여 스코프가 있는 경우 다음과 같은 순서로 동작된다.

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

여러 테스트를 수행할 때 반복적으로 작업해야 하는 것이 있다면 제스트에서도 hook을 걸어 사용할 수 있다.


참고 자료
Jest 공식문서

profile
블로그 티스토리로 이전했어요! ⇒ https://reasonz.tistory.com/

0개의 댓글