React Setting up Vite with Jest: Difference between revisions
Jump to navigation
Jump to search
Line 64: | Line 64: | ||
npm install @testing-library/react @testing-library/jest-dom --save-dev | npm install @testing-library/react @testing-library/jest-dom --save-dev | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Install jest-environment-jsdom as it no longer shipped by default | |||
<syntaxhighlight lang="bash"> | |||
npm i jest-environment-jsdom -D | |||
</syntaxhighlight> | |||
Add it to the jest.config.cjs so it now looks like this | |||
<syntaxhighlight lang="bash"> | |||
module.exports = { | |||
preset: 'ts-jest', | |||
testEnvironment: "jest-environment-jsdom", | |||
} | |||
</syntaxhighlight> | |||
Create jest-environment-jsdom.cjs | Create jest-environment-jsdom.cjs | ||
<syntaxhighlight lang="js"> | <syntaxhighlight lang="js"> | ||
module.exports = { | module.exports = { |
Revision as of 03:37, 24 September 2023
Introduction
This is a page to help set up vite with jest which did not work out of the box
Steps
Setup Project
Create project
npm init vite@latest demo-project -- --template react-ts
Add Node Engine
{
"name": "demo-project",
"version": "0.0.0",
"engines":{
"node": ">=16.13.0",
"npm": ">=8.1.0"
},
// ...
}
Install and test Jest
Install Jest
npm install jest --save-dev
Add to packages Test
"scripts":{
// ...
"test": "jest"
},
Add a dummy test in __test__/demo.test.js. Note the js
test('demo', () => {
expect(true).toBe(true)
})
Running the test should work
npm run test
Setup Typescript
Next lets use typescript
npm install ts-jest @types/jest --save-dev
And tell jest to use typescript in jest.config.cjs
module.exports = {
preset: 'ts-jest',
}
Note the cjs and not js. This is quite important and will produce the error
ReferenceError: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/home/iwiseman/dev/projects/vite_bunler/demo-project/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///home/iwiseman/dev/projects/vite_bunler/demo-project/jest.config.js:1:1
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
Add other Testing libraries
Now lets add react testing library
npm install @testing-library/react @testing-library/jest-dom --save-dev
Install jest-environment-jsdom as it no longer shipped by default
npm i jest-environment-jsdom -D
Add it to the jest.config.cjs so it now looks like this
module.exports = {
preset: 'ts-jest',
testEnvironment: "jest-environment-jsdom",
}
Create jest-environment-jsdom.cjs
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jest-environment-jsdom'
}
And a Test case
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import App from '../App'
it('renders hello message', () => {
render(<App />)
expect(screen.getByText('Hello Vite + React!')).toBeInTheDocument()
})