[Node] Express + Typescript에서 Jest로 테스트하기 - 셋업 & 해제

tkppp·2022년 9월 1일
0

Jest

목록 보기
4/5

테스트 이전 DB 연결과 같은 작업이 필요할 수 있다. Jest는 훅 함수를 통해 SetupTearDown 작업을 지원한다

훅 함수

beforeEach, afterEach

매 테스트 마다 반복하는 작업을 지정할 때 사용

beforeEach(() => {
  initializeCityDatabase();
});

afterEach(() => {
  clearCityDatabase();
});

test('city database has Vienna', () => {
  expect(isCity('Vienna')).toBeTruthy();
});

test('city database has San Juan', () => {
  expect(isCity('San Juan')).toBeTruthy();
});

비동기 작업에 대해서는 이전 포스트와 같은 방법으로 셋업과 해제 콜백을 작성하면 된다

beforeAll, afterAll

테스트 시 단 한번 수행되는 작업을 지정할 때 사용

훅 함수의 스코프와 순서

상위 스코프에서 정의된 beforeEach, afterEach는 하위 스코프의 테스트에서도 실행되고 영향을 준다

같은 레벨의 훅 함수의 실행 우선 순위는 아래와 같다

  • beforeAll > beforeEach > afterEach > afterAll

같은 레벨의 훅 함수의 실행 우선 순위는 아래와 같다

  1. 상위 스코프의 beforeAll
  2. 하위 스코프의 beforeAll
  3. 상위 스코프의 beforeEach
  4. 하위 스코프의 beforeEach
  5. 하위 스코프의 afterEach
  6. 상위 스코프의 afterEach
  7. 하위 스코프의 afterAll
  8. 상위 스코프의 afterAll
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와 test의 실행 순서

describe 내 test를 제외한 부분이 먼저 실행된 후 test가 작성된 순서대로 테스트가 실행된다

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

약간의 팁 - skip, only

describe, test 뒤에 skip(), only()를 추가함으로서 테스트를 스킵하거나 해당 테스트만 실행할 수 있다

only를 통해 실패하는 테스트만 실행하는 것이 가능하고 반대로 skip을 통해 통과하는 테스트를 테스트에서 제외하고 실패하는 테스트만 실행하는 것이 가능하다

test.only('this will be the only test that runs', () => {
  expect(true).toBe(false);
});

test('this test will not run', () => {
  expect('A').toBe('A');
});

0개의 댓글