React Testing Library
Setup
npm install --save-dev @testing-library/react
Add Librariesβ
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"jest": "^26.6.0",
Simple Codeβ
import {render, screen} from "@testing-library/react";
import Home from "./Home";
import {QueryClient, QueryClientProvider} from "react-query";
const queryClient = new QueryClient()
describe('Home Page', () => {
it('should render my name', () => {
render(<QueryClientProvider client={queryClient}><Home/></QueryClientProvider>)
screen.getByText("Melchor Tatlonghari")
});
});
Pitfallsβ
- Use
MemoryRouter
To initialize pages inside React-Router - Make sure it runs on pre-commit otherwise there is no purpose
Typescript
setupβ
Install librariesβ
npm i -D jest typescript && npm i -D ts-jest @types/jest && npx ts-jest config:init && npm test or npx jest
Configurationsβ
- config:
"jest": {
"testMatch": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[jt]s?(x)",
"!**/mock-data/**/*.[jt]s?(x)"
]
},
- jest.config.js:
- See definitions of
testEnvironment
, eithernode || jsdom
- use jsdom for web applications.
- See definitions of
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
};
Importsβ
- necessary import per file
import '@testing-library/jest-dom';
OR - Have a
setupTests.ts
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
Optionalβ
- tsconfig.json
- Prohibits installation
"exclude": [
"src/**/*.test.ts",
"src/**/*.test.tsx",
]
Pitfallsβ
Make sure these files are correct!
- jestconfig.js
moduleDirectories
preset
- type of configurationmoduleNameMapper
- tsconfig.js
sampleβ
ts.config
{
"compilerOptions": {
"target": "es5",
"lib": [
"es6",
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
],
}
{
"compilerOptions": {
"baseUrl": "./src",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}