른록노트

[Javascript] Jest - Setup and Teardown 본문

Programming/[Javascript]

[Javascript] Jest - Setup and Teardown

른록 2021. 12. 4. 23:22

Setup and Teardown

테스트를 작성하는 동안 테스트를 실행하기 전에 수행해야 하는 설정 작업과 테스트 실행 후에 수행해야 하는 마무리 작업이 있는 경우가 많습니다. Jest는 이를 처리하기 위한 도우미 기능을 제공합니다.

Repeating Setup For Many Tests

많은 테스트를 위해 반복적으로 수행해야 하는 작업이 있는 경우 beforeEach 및 afterEach를 사용할 수 있습니다.

각 테스트가 시작 또는 종료 되기전에 실행합니다.

예를 들어 여러 테스트가 도시 데이터베이스와 상호 작용한다고 가정해 보겠습니다.
이러한 각 테스트 전에 호출해야 하는 initializeCityDatabase() 메서드와 이러한 각 테스트 후에 호출해야 하는 clearCityDatabase() 메서드가 있습니다. 다음과 같이 할 수 있습니다.

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

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

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

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

beforeEach 및 afterEach는 테스트가 비동기 코드를 처리할 수 있는 것과 동일한 방식으로 비동기 코드를 처리할 수 있습니다. done 매개변수를 사용하거나 promise을 반환할 수 있습니다. 예를 들어, initializeCityDatabase()가 데이터베이스가 초기화 될 때 해결된 promise를 반환했다면 우리는 그 promise를 반환하고 싶을 것입니다:

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

One-Time Setup

어떤 경우에는 파일 시작 부분에서 한 번만 설정하면 됩니다. 이는 설정이 비동기식일 때 특히 성가실 수 있으므로 인라인으로 수행할 수 없습니다. Jest는 이러한 상황을 처리하기 위해 beforeAll 및 afterAll을 제공합니다.

전체 테스트가 시작 또는 종료 되기전에 한번만 실행합니다.

beforeAll(() => {
  return initializeCityDatabase();
});

afterAll(() => {
  return clearCityDatabase();
});

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

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

Scoping

기본적으로 before 및 after 블록은 파일의 모든 테스트에 적용됩니다. describe 블록을 사용하여 테스트를 그룹화할 수도 있습니다. describe 블록 내부에 있을 때 이전 및 이후 블록은 해당 describe 블록 내의 테스트에만 적용됩니다. 예를 들어 도시 데이터베이스뿐만 아니라 음식 데이터베이스도 있다고 가정해 보겠습니다. 다른 테스트에 대해 다른 설정을 수행할 수 있습니다.

// Applies to all tests in this file
beforeEach(() => {
  return initializeCityDatabase();
});

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

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

describe('matching cities to foods', () => {
  // Applies only to tests in this describe block
  beforeEach(() => {
    return initializeFoodDatabase();
  });

  test('Vienna <3 veal', () => {
    expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
  });

  test('San Juan <3 plantains', () => {
    expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
  });
});

최상위 beforeEach는 describe 블록 내에서 beforeEach보다 먼저 실행됩니다. 모든 후크의 실행 순서를 설명하는 데 도움이 될 수 있습니다.

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

Order of execution of describe and test blocks

Jest는 실제 테스트를 실행하기 전에 테스트 파일의 모든 describe handler를 실행합니다. 이것은 describe 블록 내부가 아니라 before* 및 after* 핸들러 내부에서 setup 및 teardown을 수행하는 또 다른 이유입니다. describe 블록이 완료되면 기본적으로 Jest는 수집 단계에서 발생한 순서대로 모든 테스트를 연속적으로 실행하고 계속 진행하기 전에 각 테스트가 완료되고 정리될 때까지 기다립니다.

describe('outer', () => {
  console.log('describe outer-a');

  describe('describe inner 1', () => {
    console.log('describe inner 1');
    test('test 1', () => {
      console.log('test for describe inner 1');
      expect(true).toEqual(true);
    });
  });

  console.log('describe outer-b');

  test('test 1', () => {
    console.log('test for describe outer');
    expect(true).toEqual(true);
  });

  describe('describe inner 2', () => {
    console.log('describe inner 2');
    test('test for describe inner 2', () => {
      console.log('test for describe inner 2');
      expect(false).toEqual(false);
    });
  });

  console.log('describe outer-c');
});

// describe outer-a
// describe inner 1
// describe outer-b
// describe inner 2
// describe outer-c
// test for describe inner 1
// test for describe outer
// test for describe inner 2

General Advice

테스트가 실패하면 가장 먼저 확인해야 할 사항 중 하나는 실행되는 유일한 테스트일 때 테스트가 실패하는지 여부입니다. Jest로 하나의 테스트만 실행하려면 해당 테스트 명령을 일시적으로 test.only로 변경하십시오.

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

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

전체로 실행할 때 자주 실패하는 테스트가 있지만 단독으로 실행할 때는 실패하지 않는 경우 다른 테스트의 무언가가 이 테스트를 방해하고 있을 수 있습니다. 종종 beforeEach로 일부 공유 상태를 지워서 이 문제를 해결할 수 있습니다. 일부 공유 상태가 수정되고 있는지 확실하지 않은 경우 데이터를 기록하는 beforeEach를 시도할 수도 있습니다.

참고사이트

공식사이트 Setup and Teardown v27.2

진행사항

### 초급

1. 공식 홈페이지에서 개념정리 
2. 공식 홈페이지에서 튜토리얼 or 가이드 실습하기 (진행)

### 중반

1. 실제로 프로젝트 만들기
2. 프로젝트 진행하면서 API DOC 찾아보며 정리하기

### 후반

1. 오픈소스 컨트리뷰트
반응형
Comments