Setting up jest & react-testing-library with React TypeScript Vite project

PHOTO EMBED

Sun Apr 30 2023 12:27:57 GMT+0000 (Coordinated Universal Time)

Saved by @kebin20 #css #sass #react.js

//Once React project is made with TypeScript do the following:

//install main dependency of jest
npm i jest --save-dev

//Install react-testing-library packages:

npm i @testing-library/jest-dom @testing-library/react @testing-library/user-event --save-dev

//If using CSS Modules
npm i jest-css-modules-transform

// If using Jest 28 or higher
npm i jest-environment-jsdom

//You will then need: 
//1. jest.config.cjs
module.exports = {
  transform: {
    "^.+\\.(t|j)sx?$": ["@swc/jest"],
    "^.+\\.jsx?$": "babel-jest",
    "^.+\\.css$": "jest-css-modules-transform",
  },
  testEnvironment: "jest-environment-jsdom",
  setupFilesAfterEnv: ["./jest.setup.tsx"],
  preset: "ts-jest",
  testMatch: ["<rootDir>/src/**/*.test.(ts|tsx)"],
  // If SVG needs to be mocked
  moduleNameMapper: {
    "\\.svg$": "<rootDir>/svgMock.tsx",
  },
};

//2. jest.setup.tsx
import '@testing-library/jest-dom';
import '@testing-library/jest-dom/extend-expect';

declare global {
  namespace NodeJS {
    interface Global {
      fetch: jest.Mock;
    }
  }
}

//3. (OPTIONAL) for svg mock; svgMock.tsx:
module.exports = '';

//Excerpt from Bing search:
//It seems like you are trying to import an SVG file as a React component in your test file. This causes Jest to throw an error because it cannot parse the SVG file as JavaScript. You need to mock the SVG file so that Jest can ignore it during testing. You can do this by using the moduleNameMapper option in your Jest configuration and mapping the SVG files to a mock file that returns an empty string or a dummy component

//Therefore, ideally package.json should look like:
{
  "name": "vite-react-starter",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test": "jest --watch"
  },
  "dependencies": {
    "@swc/jest": "^0.2.26",
    "firebase": "^9.17.2",
    "jest-css-modules-transform": "^4.4.2",
    "jest-environment-jsdom": "^29.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^14.0.0",
    "@types/jest": "^29.5.1",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.10",
    "@vitejs/plugin-react": "^3.0.1",
    "jest": "^29.5.0",
    "ts-jest": "^29.1.0",
    "typescript": "^4.9.5",
    "vite": "^4.0.4"
  }
}
content_copyCOPY