React Setting up Vite with Jest: Difference between revisions
Jump to navigation
Jump to search
Line 68: | Line 68: | ||
module.exports = { | module.exports = { | ||
preset: 'ts-jest', | preset: 'ts-jest', | ||
testEnvironment: 'jest-environment-jsdom' | testEnvironment: 'jest-environment-jsdom' | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 03:14, 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
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()
})