본문 바로가기
boostcamp-challenge

[7/23] JEST: Test 라이브러리는 이렇게 섹시하구나

by blopz 2024. 7. 23.

라이브러리 정하기

Jest 이전에는 자바스크립트 코드를 테스트하라면 여러가지 테스팅 라이브러리를 조합해서 사용하곤 했었다.예를 들어, Mocha나 Jasmin을 Test Runner로 사용하고, Chai나 Expect와 같은 Test Mathcher를 사용했으며, 또한 Sinon과 Testdouble 같은 Test Mock 라이브러리도 필요했었다.이 라이브러리들은 굉장히 유사하지만 살짝씩 다른 API를 가지고 있었기 때문에, 여러 프로젝트에 걸쳐서 일하는 자바스크립트 개발자들에게 혼란을 주기도 했었다.
하지만 Jest는 라이브러리 하나만 설치하면, Test Runner와 Test Mathcher 그리고 Test Mock 프레임워크까지 제공해주기 때문에 현재 대세라고 말할 수 있다.
출처: https://inpa.tistory.com/entry/JEST-📚-jest-문법-정리 [Inpa Dev 👨‍💻:티스토리]

 

여기서 Test Runner와 Test Matcher, 그리고 Test Mock이란???

  • Test Runner:

테스트 러너는 테스트 케이스를 실행하고 그 결과를 보고하는 프로그램입니다.

테스트 스위트를 관리하고, 테스트 실행 순서를 제어하며, 테스트 결과를 수집하고 보고서를 생성합니다.

  • Test Matcher:

테스트 매처는 테스트의 예상 결과와 실제 결과를 비교하는 데 사용되는 함수나 메서드입니다.

주로 assertion 라이브러리의 일부로 제공되며, 테스트 결과의 정확성을 판단하는 데 도움을 줍니다.

  • Test Mock:

테스트 목은 실제 객체의 동작을 모방하는 가짜 객체입니다.

외부 의존성을 단순화하거나, 특정 상황을 시뮬레이션하거나, 테스트 중인 코드의 동작을 검증하는 데 사용됩니다.

 

아무튼 이러한 이유로 Mocha보다는 Jest를 선택했다.

 

테스트환경 구축하기

> npm i -D jest 로 jets를 설치해주고

package.json
  "scripts": {
    "test": "jest"
  },

package.json에 해당 단락을 추가해 jest로 test하도록 한다

 

npm test로 이제 jest testing이 가능하다!

 

각종 메소드들은 여기서 확인했다.

 

https://velog.io/@skyu_dev/Jest-%ED%85%8C%EC%8A%A4%ED%8A%B8-%EC%BD%94%EB%93%9C%EB%A5%BC-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-JS%EC%9D%98-%EA%B8%B0%EB%8A%A5-%EC%A0%90%EA%B2%80%ED%95%98%EA%B8%B0

 

[Jest] 테스트 코드로 JS 의 기능 및 로직 점검하기

Jest를 사용해서 JavaScript 코드를 테스트하고 버그를 줄여보자

velog.io

 

TroubleShooting

E:\Git\boostcamp-challenge\Day07>npm test

> test
> jest

 FAIL  ./main.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    E:\Git\boostcamp-challenge\Day07\main.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { Path } from "./Path.js";
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.483 s
Ran all test suites.

 

실행해보니 위와 같은 Error가 발생해서 아래 문서에서 해결방법을 찾아 적용했다

 

image


https://stackoverflow.com/questions/58613492/how-to-resolve-cannot-use-import-statement-outside-a-module-from-jest-when-run

 

How to resolve "Cannot use import statement outside a module" from Jest when running tests?

I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run yarn jest, I get the following error: I have tried removing all package...

stackoverflow.com

 

위 방법을 사용하면 "type": "module"을 더이상 사용하지 못함에 유의해야한다.

 

테스트코드 짜고 실행시켜보자!

테스트코드는 보안상 삭제했다...

진짜 너무이쁘다

 

npm test를 입력하면 이렇게 섹시하게 test결과를 알려준다

 

나중에 수정사항이 생겨도 test code를 실행시키면 바뀐 코드가 제대로 작동하는지 바로 test 해볼수 있다

 

이래서 쓰는거구나.