This content originally appeared on DEV Community and was authored by Shelner
Environment
I’m using React, Vite, and TypeScript
Prepare a environment
npm create vite@latest
-> select React
-> select typescript
Install dependencies
npm install -D @testing-library/jest-dom @testing-library/react @testing-library/user-event @types/jest babel-jest identity-obj-proxy jest jest-environment-jsdom jsdom ts-jest
Create a tsconfig.test.json
/tsconfig.test.json
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true,
"jsx": "react-jsx",
"types": [
"jest",
"@testing-library/jest-dom"
]
},
"include": [
"**/*.test.tsx",
"**/*.test.ts",
"./jest.config.js",
"tests",
"src"
]
}
Create a jest.config.js
/jest.config.js
export default {
testEnvironment: 'jsdom', // for DOM testing
transform: {
'^.+\\.(t|j)sx?$': [
'ts-jest',
{ tsconfig: 'tsconfig.test.json' }
],
},
moduleNameMapper: {
// Handle CSS imports (Vite style)
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
'\\.(svg|png|jpg|jpeg|gif|webp|avif)$': '<rootDir>/__mocks__/fileMock.js',
},
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
};
Create a Mock
/__mocks__/fileMock.js
module.exports = 'test-file-stub';
Create a firs test
/src/App.test.tsx
import { render, screen } from '@testing-library/react';
import App from "./App"
it('renders React text', () => {
render(<App />);
expect(screen.getByText('Vite + React')).toBeInTheDocument();
});
Create a setupTests.ts
/src/setupTests.ts
import '@testing-library/jest-dom';
Add scripts
package.json
"test": "jest",
"test:watch": "jest --watch"
For svg
/src/custom.d.ts
declare module '*.svg' {
const content: string;
export default content;
}
Run test
npm run test
Successfully! Your first test for React, Vite, TypeScript, Jest, and React Testing Library!
This content originally appeared on DEV Community and was authored by Shelner
