JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstooling
Prev
tooling
mid
testing

How do you set up a testing environment with Jest?

jest
testing
configuration
setup
Quick Answer

Set up Jest by installing it, creating jest.config.js with settings like testEnvironment, transform for TypeScript/Babel, setupFilesAfterEnv for test utilities, and coverage configuration. Integrate with React Testing Library for component tests.

Detailed Explanation

Jest Setup:

  1. Install Jest and dependencies
  2. Create jest.config.js
  3. Add test scripts to package.json
  4. Set up test utilities (setupTests.js)

Key Configuration:

  • testEnvironment: jsdom for browser, node for Node
  • transform: Babel or ts-jest for transpilation
  • moduleNameMapper: Path aliases
  • setupFilesAfterEnv: Test setup files
  • coverage: Coverage settings

With React:

  • @testing-library/react
  • @testing-library/jest-dom
  • @testing-library/user-event

Code Examples

Jest configuration
// jest.config.js
module.exports = {
  // Test environment
  testEnvironment: 'jsdom',
  
  // Setup files
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
  
  // Transform TypeScript/JSX
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
  },
  
  // Module aliases (match tsconfig paths)
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '\\.(css|less|scss)$': 'identity-obj-proxy',
  },
  
  // Coverage
  collectCoverageFrom: [
    'src/**/*.{js,jsx,ts,tsx}',
    '!src/**/*.d.ts',
    '!src/index.tsx',
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
    },
  },
  
  // Test patterns
  testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'],
  testPathIgnorePatterns: ['/node_modules/', '/dist/'],
};

Resources

Jest Configuration

docs

Related Questions

What is ESLint and why should you use it?

junior
linting

How do you set up CI/CD for a JavaScript project?

mid
ci-cd
Previous
What debugging tools and techniques should you know?