본문 바로가기
JavaScript

Jest import 방법 (With @ 포함 경로 인식)

by 오근성 2023. 4. 20.
728x90

 

  1. Jest 설치 및 초기 설정:
npm install --save-dev jest @types/jest ts-jest
npx ts-jest config:init
  1. package.json 에서 Jest 스크립트 설정:
{ "scripts": { "test": "jest" } }

   3. jest.config.ts 설정 파일 예제:

import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  setupFilesAfterEnv: ['./src/setupTests.ts'],
  reporters: [
    "default",
    [
      "jest-html-reporters",
      {
        publicPath: "./html-report",
        filename: "report.html",
        expand: true,
      },
    ],
  ],
};

export default config;
  1. React 컴포넌트 예제 (MyComponent.tsx):
import React from 'react';

interface MyComponentProps {
  message: string;
}

export const MyComponent: React.FC<MyComponentProps> = ({ message }) => {
  return <div>{message}</div>;
};
  1. 테스트 코드 예제 (MyComponent.test.tsx):
import React from 'react';
import { render, screen } from '@testing-library/react';
import { MyComponent } from './MyComponent';

describe('MyComponent', () => {
  test('renders the correct message', () => {
    const message = 'Hello, World!';
    render(<MyComponent message={message} />);
    expect(screen.getByText(message)).toBeInTheDocument();
  });
});
  1. setupTests.ts 파일 예제 (Jest와 React Testing Library 설정):
import '@testing-library/jest-dom';

 

Jest를 설치하고 설정하는 방법, React 컴포넌트와 테스트 코드 예제, 그리고 Jest 설정 파일에서 리포터를 사용하여 테스트 결과를 다른 형식으로 출력하는 방법에 대해 설명했습니다.

728x90

댓글