npm i jest -D
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "jest"
},
yarn add -D @babel/preset-env @babel/preset-react
Create a .babelrc
file:
{
"presets": [
"@babel/preset-env",
["@babel/preset-react", { "runtime": "automatic" }]
]
}
npm i @testing-library/react @testing-library/jest-dom -D
To support web environment API, install jest-environment-jsdom add into jest config in package.json:
npm i jest-environment-jsdom -D
"jest": {
"testEnvironment": "jsdom",
}
"jest": {
"testEnvironment": "jsdom",
"setupFilesAfterEnv": [
"<rootDir>/setupTests.js"
]
}
Create setupTests.js file:
import "@testing-library/jest-dom";
npm run test
npm i @testing-library/user-event@latest -D
npm install --save-dev @types/jest
-
getBy
queries:getByText
getByPlaceholderText
getByLabelText
getByAltText
getByTestId
// throws an error if the element is not found.
-
queryBy
queries:- return null if element not found
-
findBy
queries:- asynchronous versions of the
getBy
- should use async await
- asynchronous versions of the
-
getAllBy
-
queryAllBy
-
findAllBy
-
within
- Allows you to narrow the scope of your queries to a specific element, useful for testing within specific sections of your component.
-
UserEvent
-
fireEvent
-
screen