본문 바로가기

TIL

Jest with Webpack

 

순서

  1. jest 설치 
  2. App.test.js 파일 작성
  3. 에러 두가지 
        The error below may be caused by using the wrong test environment
              - docblock이란? ???? ?
              - 해결 : 주석설정
        TypeError: expect(...).toBeInTheDocument is not a function
             - 해결 : import "@testing-library/jest-dom";
  4. 설정 성공!

 

 

 

Webpack에 Jest설정을  해보자 

 

 

Jest · 🃏 Delightful JavaScript Testing

🃏 Delightful JavaScript Testing

mulder21c.github.io

 

 

 

 

jest 설치 

 


 

npm install --save-dev jest

 

 

 

package.json파일에 추가 

 

{
  "scripts": {
    "test": "jest"
  }
}

 

 

 

 

 

 

😆 와앙 다됐다 npm test해보자아아

 

테스트 파일은 간단한 친구

Hello와 WEBPACK이 있는지 보는 test!

 

 

App.tsx

import React from "react";

const App = () => {
  return <div style={{ margin: "400px" }}>Hello WEBPACK!!!!!</div>;
};

export default App;

 

 

 

App.test.js

 

import { render, screen } from "@testing-library/react";
import App from "./App";

test("renders learn react link", () => {
  render(<App />);
  const linkElement = screen.getByText(/Hello Webpack/i);
  expect(linkElement).toBeInTheDocument();
});

 

 

 

 

그리고 호기롭게 명령어 치기

 

 

npm test

 

 

 

 

🥹 에러 :


The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.

 

 

에러의 원인 

잘못된 테스트 환경? 

The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.

 

 

 

 

주석을 테스트 파일 최상단에 적어놓기

 

 

/**
 * @jest-environment jsdom
 */

 

 

 

😯 뭐야뭐야 저게 뭐야? 그냥 주석 아니야? : jest docblock이란 것이란다.

 

🤔 나는 안깔았는데....?

 

package.json에는 없었는데 package-lock.json에는 있다!

 "node_modules/jest-docblock": {
      "version": "29.7.0",
      "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz",
      "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==",
      "dev": true,
      "dependencies": {
        "detect-newline": "^3.0.0"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },

 

누가 깔았어... 아마도.. jest가 가져왔나봐 그건 나중에 또 더 파보자구 친구... 

 

 

 

 

 

 

🤔 알았어 일단 너의 소개를 들어보도록 하자 

 

"docblock은 스페셜하게 포맷되어있는 코멘트라고요. 파일 맨위에 있어요!"

https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md

 

 

jest-docblock is a package that can extract and parse a specially-formatted comment called a "docblock" at the top of a file.
A docblock looks like this:

 

 

👉 요런식으로 써요.

/** * Stuff goes here! */

 

👉 프래그램도 포함할 수 있어요. 그게 뭔말이냐하면 @로 프리픽스 될수 있는 단어라는거에요.

/** * Pragma incoming! * * @flow */

 

 

 

오... 너구나 ... 

내가 써서 성공한 친구... .

예측하건대, 

jest-docblock은 뭐든 가져올 수 있고, 

내 node_modules에있는 

@jest-environment jsdom란 친구를 가져온 것. 

친구 소개해준 친구.... 

 

jest-docblock이 할수 있는 것:

extract the docblock from some code as a string
parse a docblock string's pragmas into an object
print an object and some comments back to a string 

코드에서 docblock을 문자열로 추출 

스트링의 프래그마를 객체의 docblock으로 파싱

객체와 주석을 문자열로 출력

 

코드에서 docblock을 추출하고 분석하여 정보를 객체로 변환하고 문자열로 출력할 수 있는 도구란 의미

 

 

 

나의 부족한 실력을 채워줄 다른 분의 블로그 

 

 

[Jest] 특정 테스트 파일의 config 만 업데이트 하기

일반적으로 Jest 를 실행할때는 환경별로 jest config 설정을 다르게 지정해놓고 많이 사용들을 한다.jest 의 config 에는 setupFiles 라는 옵션이 있는데, 테스트가 실행되기 전에 해당 파일을 import 해서

velog.io

 

 

Jest를 실행할 때는 환경별로 jest config설정을 지정하지만, 

특정 파일에 대해 설정을 할 수 있다.

지금은 jsdom을 가져왔으나, 

커스터마이징 해서 가져올 수도 있다. 

 

 

 

 

 

App.test.js 파일 작성 해보기


 

 

/**
 * @jest-environment jsdom
 */
import { render, screen } from "@testing-library/react";
import App from "./App";

test("renders learn react link", () => {
  render(<App />);
  const linkElement = screen.getByText(/Hello Webpack/i);
  expect(linkElement).toBeInTheDocument();
});

 

 

 

에러 :  TypeError: expect(...).toBeInTheDocument is not a function

 

 

 

나의 스택선생님 가라사대.... 

toBeInTheDocument is not part of RTL. You need to install jest-dom to enable it.
And then import it in your test files by:

 

 

react-testing-library why is toBeInTheDocument() not a function

Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none. it('should show and hide the message using onMouseOver and onMouseOut events

stackoverflow.com

 

RTL의 분야가 아니라서 jest-dom을 설치해야 하고 import 해야 한단다!!!!

현재 jest-dom은 없는데 ... 나에게 깔려있는 친구들로 되나보다 

 

  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-jest": "^29.7.0",
    "html-webpack-plugin": "^5.5.4",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "webpack-dev-server": "^4.15.1"
  },
  "devDependencies": {
    "@babel/core": "^7.23.6",
    "@babel/preset-env": "^7.23.6",
    "@babel/preset-react": "^7.23.3",
    "@babel/preset-typescript": "^7.23.3",
    "@testing-library/dom": "^9.3.3",
    "@types/react": "^18.2.45",
    "@types/react-dom": "^18.2.18",
    "babel-loader": "^9.1.3",
    "esbuild-loader": "^4.0.2",
    "jest": "^29.7.0",
    "ts-loader": "^9.5.1",
    "typescript": "^5.3.3",
    "webpack": "^5.89.0",
    "webpack-cli": "^5.1.4"
  }

 

 

일단 import하고 

 

import "@testing-library/jest-dom";

 

test를 실행해보니 정상적으로 테스트에 성공하게 되었다.

 

 

겪었던 에러 몇가지 는 다른 글에 

 

[jest & webpack] 에러 몇가지 "jest-environment-jsdom" is no longer shipped by default, Cannot find module, Configuration er

1) As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately. 에러의 원인 module이 설치되어있지 않았음 에러 해결 jest-environment-jsdom 설치 npm install -D jest-environment-jsdom 2) Cann

wha-haha.tistory.com