Remark: I follow here the steps in the reference paper (see credits).
Part 1 relates to pure typescript jest
Part 2 relate to the testing library in general and to react in particular
- create a vite react typescript project using npm init vite@latest and choosing react and ts
- npm i -D jest @types/jest
- add to scripts in package.json
"test" : "jest"
- create directory test under src (not mandatory but common practice) and create there a test file <file_name>.test.tsx e.g Person.test.tsx for component and <file_name>.test.ts for non component
- npm i -D ts-jest ts-node
- create jest.config.ts file and add
export default { transform: { "^.+\\.tsx?$": "ts-jest" } }
transform is required because jest run javascript code, so we need to tell it how to transform tsx files to javascript. Done using the module ts-jest
- import Person.css will fail in jest. jest is a javascript testing library so it does not know to handle css file. Bypass the error by adding the following to jest.config.ts
moduleNameMapper: { '\\.(css|less|sass|scss)$': 'identity-obj-proxy', }
and by install : npm i -D identity-obj-proxy
- as of jest 28
npm i -D jest-environment-jsdom
- npm i -D @testing-library/react @testing-library/user-event
- npm i -D @testing-library/jest-dom
- add testEnvironment: "jsdom" to export default inside jest.config.ts
- Jest is a javascript framework for testing. It will ignore CSS files. Thus using jest, you can not do visual tests, e.g., verify that a button color is red if imported from a CSS file. Jest works fine with inline styling, i.e., css-in-js.
What is your options if you have css files ? Use visual test tools like cypress check e.g. this 31:45