React Setting up Vite with Jest

From bibbleWiki
Revision as of 03:05, 24 September 2023 by Iwiseman (talk | contribs) (Created page with "=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 <syntaxhighlight lang="bash"> npm init vite@latest demo-project -- --template react-ts </syntaxhighlight> Add Node Engine <syntaxhighlight lang="js"> { "name": "demo-project", "version": "0.0.0", "engines":{ "node": ">=16.13.0", "npm": ">=8.1.0" }, // ... } </syntaxhighlight> ==Install and test Jest== Install Jest <synta...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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)