Next.js + Jest + Typescript 환경 세팅하기

BinaryWoo_dev·2023년 3월 14일
0

리액트 테스트

목록 보기
2/5

NextJS 프로젝트 생성

$yarn create next-app

#or 

$npx create-ext-app@latest

#or 

$pnpm create next-app

관련 패키지 설치

Typescript 관련 패키지

패키지 설치

$yarn add --dev typescript

Jest 관련 패키지

패키지 설치

 $yarn add --dev jest @jest/globals jest-dom jest-environment-jsdom jsdom ts-jest ts-loader

React Testing Library 관련 패키지

패키지 설치

$yarn add --dev @testing-library/dom @testing-library/jest-dom @testing-library/react @testing-library/user-event

Babel 관련 패키지

패키지 설치

$yarn add --dev @babel/core babel/jest @babel/plugin-syntax-jsx @babel/plugin-proposal-optional-chaining @babel/preset-env @babel/preset-typescript

환경 설정

typescript

환경 파일 생성

$yarn tsc

Jest

jest.config.js

module.exports = {
  collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.d.ts', '!**/node_modules/**'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleNameMapper: {
    // Handle CSS imports (with CSS modules)
    // https://jestjs.io/docs/webpack#mocking-css-modules
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',

    // Handle CSS imports (without CSS modules)
    '^.+\\.(css|sass|scss)$': '<rootDir>/styles/__mocks__/styleMock.js',

    // Handle image imports
    // https://jestjs.io/docs/webpack#handling-static-assets
    '^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': `<rootDir>/__mocks__/fileMock.js`,

    // Handle module aliases
    '^@/pages/(.*)$': '<rootDir>/pages/$1',
    '^@/components/(.*)$': '<rootDir>/components/$1',
    '^@/styles/(.*)$': '<rootDir>/styles/$1',
    '^@/static/(.*)$': '<rootDir>/static/$1',
    '^@/types/(.*)$': '<rootDir>/types/$1'
  },
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  testEnvironment: 'jest-environment-jsdom',
  transform: {
    // Use babel-jest to transpile tests with the next/babel preset
    // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
    	'\\.[jt]sx?$': 'ts-jest' // Typescript 를 사용할 경우
	    '\\.[j]sx?$': 'babel-jest' // javascript 만 사용할 경우
  },
  transformIgnorePatterns: ['/node_modules/', '^.+\\.module\\.(css|sass|scss)$'],
  verbose: true,
  preset: 'ts-jest',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  type: 'module'
  testEnvironmentOptions: {
    url: 'http://localhost/',
  },
};

Babel

.babelrc or babel.config.json

  {
    "presets": [
      ["@babel/preset-env", {"targets": {"node": "current"}}],
      "@babel/preset-typescript",
      "next/babel"
    ],
    "plugins": [
      [
        "module-resolver", {
          "root": ["."],
          "alias": {
            "styles": "./styles"
          },
          "cwd": "babelrc"
      }],
      ["@babel/plugin-transform-modules-commonjs", { "allowTopLevelThis": true }]
      ["@babel/plugin-proposal-optional-chaining"],
      ["@babel/plugin-syntax-jsx"]
    ],
    "ignore": []
  }
  • "presets" 설정 부분에서 설정 순서를 유의해야 한다. 나같은 경우에 처음에는
  "presets": [
      ["@babel/preset-env", {"targets": {"node": "current"}}],
      "@babel/preset-typescript",
      ["@babel/preset-react", {{"runtime": "automatic"}]
  ],

순서로 적용했었는데, cannot import outside a module 에러가 발생했기 때문이다.

test script 명령어

package.json

	"script" : {
    	"test": "jest --watchAll"
    }
  • --watchAll 옵션 : 내용이 변경된 파일이 있으면 자동으로 테스트를 재시작한다.

결과

profile
매일 0.1%씩 성장하는 Junior Web Front-end Developer 💻🔥

0개의 댓글