Web/JEST

JEST - snapshot

dev_sr 2023. 12. 7. 18:34

snapshot 은 어떤 기능의 예상 결과를 미리 포착해두고 결과를 비교하는 테스팅 기법이다. 

 

1. toMatchSnapshot()

snapshot을 따로 파일을 만들어서 보관한다.  아래 코드를 실행하면 snapshot 파일이 생성된다.

 

fn.js에 addNum이라는 함수를 하나 만들고 배열과 숫자를 입력받으면 

각 배열의 요소마다 입력받은 숫자를 더한 뒤 배열을 리턴하는 함수를 작성하고 

test를 진행해봤다.

//fn.js
addNum: (arr, num) => {
    arr = arr.map((el) => el + num);
    return arr;
  },
//it 과 test는 같은 함수이다
it("snapshot", () => {
  let result = fn.addNum([1, 2], 100);  // [101, 102]
  expect(result).toMatchSnapshot();
});

 

 

snapshots 디렉토리가 생기고 result의 결과가 담긴 snapshot 파일이 생겼다.  

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`snapshot 1`] = `
[
  101,
  102,
]
`;

 

 

 

fn.addNum에서 num에 2를 곱한 뒤 계산하도록 수정한 뒤 테스트를 실행해보면

addNum: (arr, num) => {
    arr = arr.map((el) => el + num * 2);
    return arr;
  },

 

친철하게 snapshot과 뭐가 다른 지 비교해주며 실패했다고 알려준다.

 

스크린 샷에 써있는 대로 npm test -- -u 명령어를 입력해보면

snapshot이 현재 테스트 결과값으로 업데이트 되며

// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`snapshot 1`] = `
[
  201,
  202,
]
`;

 

실패하던 테스트에 성공한 것을 볼 수 있다.

 

 

2. toMatchInlineSnapshot()

snapshot 을 인라인으로 만들어준다.

fn.js의 addNum을 다시 원래대로 수정하고 

//fn.js
addNum: (arr, num) => {
    arr = arr.map((el) => el + num);
    return arr;
  },

 

toMatchInlineSnapshot 를 사용하기 위해 테스트 코드를 수정해준다.

 

it("snapshot", () => {
  let result = fn.addNum([1, 2], 100);
  expect(result).toMatchInlineSnapshot();
});

 

이제 테스트를 실행하면 테스트 코드에 snapshot이 작성된다.

it("snapshot", () => {
  let result = fn.addNum([1, 2], 100);
  expect(result).toMatchInlineSnapshot(`
[
  101,
  102,
]
`);
});

 

이번엔 addNum 함수를 num에 3을 곱한 뒤 더하도록 수정해본다.

addNum: (arr, num) => {
    arr = arr.map((el) => el + num * 3);
    return arr;
  },

 

테스트를 실행해보면 인라인으로 쓰여있는 snapshot과 다르다고 불통을 준다.

 

npm test -- -u를 똑같이 입력해보면 snapshot이 테스트한 결과값으로 수정되고 테스트에 통과된다.

it("snapshot", () => {
  let result = fn.addNum([1, 2], 100);
  expect(result).toMatchInlineSnapshot(`
[
  301,
  302,
]
`);
});

 

 

 

 

 

참고

https://www.daleseo.com/jest-snapshot/

'Web > JEST' 카테고리의 다른 글

JEST - Mock  (2) 2023.12.06
JEST - before, after, only, skip  (0) 2023.12.05
JEST - Matcher  (2) 2023.12.05