jest 学习:测试React程序

在Facebook,我们使用 Jest 测试 React 应用程序
更新于: 2022-04-25 01:03:03

初始化项目

.
├── README.md
├── package-lock.json
├── package.json
├── public
│   └── index.html
├── src
│   └── index.tsx
├── tsconfig.json
└── webpack.config.js

添加 jest 相关包 jest + jsdom + @testing-library/react

npm install @types/jest @testing-library/react @testing-library/jest-dom jest ts-jest

添加 jest 配置文件 rootDir/jest.config.js

  • 注意 src/__tests__ 这个目录下
module.exports = {
  // The root of your source code, typically /src
  // `<rootDir>` is a token Jest substitutes
  roots: ['<rootDir>/src'],
  testEnvironment: 'jsdom',
  verbose: true,

  // Jest transformations -- this adds support for TypeScript
  // using ts-jest
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },

  // Runs special logic, such as cleaning up components
  // when using React Testing Library and adds special
  // extended assertions to Jest
  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'],

  // Test spec file resolution pattern
  // Matches parent folder `__tests__` and filename
  // should contain `test` or `spec`.
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',

  // Module file extensions for importing
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  moduleNameMapper: {
    '@/(.*)': '<rootDir>/src/$1',
  }
};

添加相应的组件/测试用例,最终项目结构如下

.
├── README.md
├── jest.config.js
├── package-lock.json
├── package.json
├── public
│   └── index.html
├── src
│   ├── __tests__
│   │   └── components
│   │       └── checkbox.spec.tsx
│   ├── components
│   │   └── checkbox.tsx
│   └── index.tsx
├── tsconfig.json
└── webpack.config.js

简单的测试脚本 jest-ts-react/src/__tests__/components/checkbox.spec.tsx

import React from 'react';
import { render, fireEvent } from '@testing-library/react';

import { Checkbox } from '../../components/checkbox';

test('<Checkbox label="I Agree" /> set props label should worked', () => {
  render(<Checkbox label="I Agree" />);
  const el = document.querySelector('.rc-checkbox') as HTMLDivElement;
  const checkbox = el.querySelector('input') as HTMLInputElement;
  console.log(el.innerHTML, checkbox.checked);
  fireEvent.click(checkbox);
  console.log(el.innerHTML, checkbox.checked);
});

jest 添加 @ 根路径支持

  • 在 jest.config.js 里添加这一行
moduleNameMapper: {
    '@/(.*)': '<rootDir>/src/$1',
  },

参考

https://www.pluralsight.com/guides/how-to-test-react-components-in-typescript

https://jestjs.io/zh-Hans/docs/tutorial-react

https://www.freecodecamp.org/news/react-testing-library-tutorial-javascript-example-code/

https://testing-library.com/docs/queries/about/#screendebug