Jest 사용법 - 설정과 해체

공식문서에 있는 예제를 통해 기본적인 사용법을 빠르게 익힌다. 따라서 모든 내용은 공식 문서 기반이며, 추후에 테스트를 많이 작성하면서 발생한 엣지 케이스를 이 내용에 덧붙여 추가할 예정이다.

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();
});

만약 initializeCityDatabase가 프라미스(promise)를 반환하는 경우는 앞에서 했듯 아래와 같이 작성하면 된다.

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

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();
});

위의 설정과 해체 블록은 describe 블록을 통해 범위 지정(Scoping)할 수 있다.

// 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 sausage', () => {
    expect(isValidCityFoodPair('Vienna', 'Wiener Würstchen')).toBe(true);
  });

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

Last updated