describe, beforeEach ,beforeAll afterEach,afterAll 에 관하여

미마모코딩·2022년 9월 11일
0

jest

목록 보기
3/3
post-thumbnail

jest에서 모두들 describe를 봤을텐데 describe는 어디다 사용하는 녀석일까?

공식문서에 따르면 describe(name, fn)여러 관련 테스트를 그룹화하는 블록을 만듭니다

라고 표기되어있다.

그렇다면 실전에선 어떻게 사용할 수 있을까?

const fn = {
  connectFoodDb: () => {
    return new Promise((res, rej) => {
      setTimeout(() => {
        res({
          name: "noodle",
          price: 25,
        });
      }, 500);
    });
  },
    disConnectFoodDb: () => {
    return new Promise((res, rej) => {
      setTimeout(() => {
        res();
      }, 500);
    });
  },
}
module.exports = fn;

위 함수를 만들고 테스팅을 보도록하자.

Db연결 코드는 아무래도 beforeAll afterAll과같이 최초 최후에 한번 해주는게 더 유리하기에

위 내용을 토대로 작성해보겠다.

describe("food관련 테스팅", () => {
  let food;
  beforeAll(async () => {
    food = await fn.connectFoodDb();
  });
  afterAll(() => {
    return fn.disConnectFoodDb();
  });

  test("food의 네임은 누들", () => {
    expect(food.name).toBe("noodle");
  });
  test("food의 price 25", () => {
    expect(food.price).toBe(25);
  });
});

이렇게 describe함수안에 food관련 테스팅 코드를 작성했다.

위에서 쓰인 beforeAll,afterAll의 동작순서와 beforeEach,afterEach의 동작순서를 우리는 잘 이해할 필요가 있다.

beforeEach란?

이 파일의 각 테스트가 실행되기 전에 함수를 실행한다.. 함수가 promise를 반환하거나 생성자인 경우 Jest는 테스트를 실행하기 전에 해당 약속이 해결될 때까지 기다린다.

beforeAll란?

beforeEach의 내용과 동일하지만 우선순위가 beforeAll 즉 제일 먼저 실행된다.

afterEach란?

이 파일의 각 테스트가 완료된 후 함수를 실행한다. 함수가 약속을 반환하거나 생성자인 경우 Jest는 계속하기 전에 해당 약속이 해결될 때까지 기다린다.

afterAll란?

afterEach의 내용과 동일하지만 beforeAll는 제일 마지막에 실행된다.

beforeAll(() => console.log("밖 beforeAll")); //1
beforeEach(() => console.log("밖 beforeEach")); //2 ,6
afterEach(() => console.log("밖 afterEach")); //4 , 10
afterAll(() => console.log("밖 afterAll")); //12

test("0+1 = 1", () => {
  expect(fn.add(0, 1)).toBe(1);
}); //3

describe("순서관련작업", () => {
  beforeAll(() => console.log("안 beforeAll")); //5
  beforeEach(() => console.log("안 beforeEach")); //7
  afterEach(() => console.log("안 afterEach")); //9
  afterAll(() => console.log("안 afterAll")); // 11

  test("0+1 =1", () => {
    expect(fn.add(0, 1)).toBe(1);
  }); //8
});

beforeAll,beforeEach,afterEach,afterAll의 동작순서를 잘 구분할 필요가 있다.

위 순서에서 중요하게 볼 내용은 beforeEach는 전역 - 지역 -테스트코드 순서로 동작 afterEach는 지역-전역 순으로 테스팅이 돌아감 이다. 두번씩 호출된 beforeEach,afterEach 의 내용을 살펴보자.

전역적으로 이미 호출이 됐어도 지역안에서 다시 beforeEach를 호출하면 지역의 beforeEach를 호출하기전에 전역부터 호출하고 지역을 호출하기에 전역 beforeEach이 6번이 되는것이다. 지역의 beforeEach는 7번이 되었다.

afterEach를 다시 한 번 지역에서 만날경우 beforeEach와 반대로 지역부터 호출되고 전역을 호출한다.

afterAll이 전역에서 존재할경우는 항상 마지막에 위치한다.

0개의 댓글