Configuration Unit Test with Jest - gloriaJun/react-realworld-example-app GitHub Wiki

Setup

Add dependencies

npm install -D jest react-testing-library
# or
yarn add -D jest react-testing-library

Add a npm script

{
  "scripts": {
    "test": "jest --config jest.config.js",
    "test:watch": "$npm_execpath test --watch",
    "test:coverage": "$npm_execpath test --coverage --colors"
  }
}

Create the config file

jest.config.js

module.exports = {
  // Automatically clear mock calls and instances between every test
  clearMocks: true,
  setupFiles: ['<rootDir>/tests/unit/testSetup.js'],
  setupFilesAfterEnv: ['react-testing-library/cleanup-after-each'],
  // collectCoverageFrom: ['src/**/*.{js,jsx}'],
  // moduleDirectories: ['src', 'node_modules'],
  moduleNameMapper: {
    '^@(.*)$': '<rootDir>/src/$1',
     // '^@components/(.*)$': '<rootDir>/src/components/$1',
     // '^@store/(.*)$': '<rootDir>/src/store/$1',
  },
  moduleFileExtensions: ['js', 'jsx', 'json'],
};

Set EsLint Configuration

env: {
  // ...SKIP...
  jest: true, // added
},

Running tests from npm script

Run all tests (default)

npm run test
# or
yarn test

Run tests with watch

npm run test:watch
# or
yarn test:watch

Run only the tests that were specified with a pattern or filename

npm run test InputText
# or
npm run test tests/unit/components/InputText.test.js
# or
npm run test InputText.test.js

Libraries

jest-silent-reporter

jest-silent-reporter

⚠️ **GitHub.com Fallback** ⚠️