Skip to content

Instantly share code, notes, and snippets.

@alexgeis
Last active May 29, 2025 04:02
Show Gist options
  • Select an option

  • Save alexgeis/e5b67cbacf4802984b4f17e0c394eed1 to your computer and use it in GitHub Desktop.

Select an option

Save alexgeis/e5b67cbacf4802984b4f17e0c394eed1 to your computer and use it in GitHub Desktop.
Jest w/ Vite + React + Typescript

Using Jest w/ Vite + React + Typescript

This gist is a guide for incorporating the testing library Jest into a Vite app using React and Typescript. Shout out to Manny for solving the labyrinth that is Vite + TypeScript + Jest

Table of Contents
  1. Dependencies
  2. Project File Structure
  3. Package.json
  4. Potential Errors

Dependencies

npm install jest @types/jest @testing-library/react @testing-library/jest-dom @testing-library/user-event ts-jest ts-node jest-environment-jsdom identity-obj-proxy

Breakdown of each package role:

  • jest
    • testing library we're using
  • @types/jest
    • Typescript types imported for Jest
  • @testing-library/react
  • @testing-library/jest-dom
  • @testing-library/user-event
    • 3 libraries above allow for testing React specifically in Jest
  • ts-jest
  • ts-node
    • 2 packages above support Jest transformation for TypeScript
  • jest-environment-jsdom
    • configure Jest to run tests with a browser environment in mind
  • identity-obj-proxy
    • tests imports that may not affect your unit tests (for example, CSS)

(back to top)

Project File Structure

// ROOT PROJECT FOLDER
jest.setup.ts
/src
    /__tests__
        [testFileName].test.tsx
/test
    /__mocks__
        fileMock.js

jest.setup.ts

import "@testing-library/jest-dom/extend-expect";

fileMock.js

module.exports = "test-file-stub";

[testFileName].test.tsx

Example test to confirm Jest is connected:

test('Renders main page correctly', () => {
  expect(true).toBeTruthy();
});

(back to top)

Package.json

I include my Jest settings within package.json. If you prefer, you can move this info to a separate jest.config.ts file (be sure to deserialize this JSON info into a JS object).

"scripts": {
		"test": "jest",
"jest": {
		"testEnvironment": "jsdom",
		"verbose": true,
		"transform": {
			"^.+\\.tsx?$": "ts-jest"
		},
		"setupFilesAfterEnv": [
			"<rootDir>/jest.setup.ts"
		],
		"moduleNameMapper": {
			"\\.(gif|ttf|eot|svg|png)$": "<rootDir>/test/__mocks__/fileMock.js",
			"\\.(css|less|sass|scss)$": "identity-obj-proxy"
		}
	},

(back to top)

Potential Errors

  1. --isolatedModules
'App.test.tsx' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module.ts(1208)

Most modules require either an import or an export. We can solve this by importing the file we intend to test:

// App.test.tsx
import App from '../App';

  1. Jest encountered an unexpected token
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

This error could be thrown by using ECAMScript Modules rather than CommonJS modules, but it's more likely that Typescript is giving you this error in Vite.

Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

Using option 4 in their provided list of remedies, we can update the transform property in our Jest configuration. (see package.json above)


  1. SyntaxError: Unexpected token '<' (importing assets/CSS)
SyntaxError: Unexpected token '<'
1 | import { useState } from 'react'
    > 2 | import logo from './logo.svg'
        | ^
      3 | import './App.css'
      4 |
      5 | function App() {

This is because we need to account and mock images and styling files. To start with the images, we’re going to create a mock file in a set of new folders to act as helpers:

  1. create in the root of the project a directory and nested directory: /test/mocks
  2. in mocks/ create a new file called "fileMock.js". (see Project File Structure above)
  3. modify our package.json (or jest.config.ts) Jest attribute moduleNameMapper to point all images to that mock file. (see package.json above)

  1. Wrong test environment
FAIL  src/__tests__/App.test.tsx
  ✕ Renders main page correctly (1 ms)
● Renders main page correctly
The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.
    
    ReferenceError: document is not defined

This is because we haven’t configured Jest to run tests with a browser environment in mind. To fix this, we’ll add a new attribute called testEnvironment and set it to "jsdom". As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.

npm install jest-environment-jsdom

(see package.json above for example of testEnvironment)

(back to top)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment