Quick Jest Setup With ViteJS, React, & TypeScript

Avoid Spending Time Setting Up Jest For Your Projects & Follow This Quick Setup

Manny
8 min readNov 1, 2021
A Walkthrough On How To Setup Jest Quickly With ViteJS, React, & TypeScript

UPDATE 2022–12–27: Also take a look at my other article on settings up Vitest with ViteJS, React, & TypeScript.

Reasons To Not Waste Time With Setup

This came when I was trying to setup a new project while doing some pair programming with some developers on Developer DAO. We wanted to test some Jest unit tests with a wallet interactions (coming soon), and found that we spent way more time trying to setup Jest than actually working on the code we actually wanted to work on.

Whenever I find myself having a hard time setting something up, I end up documenting the process to make sure I’m able to pick it up again without have to go heavy into the documentation. I also try and create template repositories for any future projects, that way I’m spending so much time on setup, and more on newer functionality.

What We’re Building

This is a walkthrough, so we’ll cover adding different libraries, why do certain configurations, and extend Jest a bit further to make things clearer.

This project will be extending a bit of the pre-existing scaffolded React TypeScript Template from ViteJS. If you ever wanted to not waste time, then follow these steps to get things setup.

TL;DR

In case you want to skip the explanation and just get straight to the code, scroll down to Final Code 👇.

Requirements

Make sure you have the following setup on your computer before going forward with the walkthrough.

  • NVM or Node 16.13.0 LTS
  • Yarn 1.22.0

Project Setup Walkthrough

Let’s start by scaffolding out our React TypeScript app with ViteJS.

What We’re Working With

First, let’s look at what we’re working with by running yarn dev and opening our site on http://localhost:3000.

Default Vitejs Scaffolded React TypeScript Project — http://localhost:3000

The scenario we’re going to test for is when the button is clicked a certain amount of times, that the state and UI increases accordingly (ie: 2 click = “count is: 2”).

Jest & Types

We’re going to start by adding jest to our project.

Adding jest and types to our project

Next we’ll modify our package.json to support a new yarn test command.

package.json

Now if we run yarn test we should see following:

No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In /path/to/your-project-folder
6 files checked.
testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 0 matches
testPathIgnorePatterns: /node_modules/ - 6 matches
testRegex: - 0 matches
Pattern: - 0 matches
error Command failed with exit code 1.

We have things installed but now we need a test.

Creating Our First Test

We’ll start by creating a new folder in our src folder called __tests__ and creating a new file called App.test.tsx.

src/__tests__/App.test.tsx

If you run yarn test you should see the following results:

❯ yarn test
yarn run v1.22.10
$ jest
PASS src/__tests__/App.test.tsx
✓ Renders main page correctly (1 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.357 s
Ran all test suites.
✨ Done in 1.90s.

⚠️ NOTE: In your IDE, you may encounter this issue when you hover over your test function.

'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)

This is because most modules require either an import or an export. We can solve this by just importing the file we intend to test App.tsx.

src/__tests__/App.test.tsx

Accounting For TypeScript

If we run our tests again with yarn test we should something similar to the following error:

$ jest
FAIL src/__tests__/App.test.tsx
● Test suite failed to run
Jest encountered an unexpected tokenJest 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.Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.By default "node_modules" folder is ignored by transformers.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.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

It mentions many ways on how you can solve this but we’re going to take advantage of option 4, which uses transform. In order to do this, we’ll need to create a new file called jest.config.ts in the root of our project and add two new modules to our project.

bash to add ts-node and ts-jest

In our configuration file we’re going to take advantage of ts-jest, which is based on ts-node, to be able to handle specific files that end in .tsx with ts-jest.

jest.config.ts

Now if you run yarn test again you’ll see it’s working, but now we need to start working with React components.

Testing React Components

In order for us to test the react component, we’re going to add two new modules.

Adding @testing-library/react and @testing-library/user-event

Next, we’ll revise our App.test.tsx to render the component we want to test.

App.test.tsx

Now if we try to run our yarn test again we’ll see that we get a set of errors we have to deal with.

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 created in the root of the project, so they act as helpers, test/__mocks__ and then create a new file called fileMock.js.

test/__mocks__/fileMock.js

We’ll then modify our jest.config.ts to point all images to that mock file using moduleNameMapper.

jest.config.ts

If we run yarn test again we’ll see that things are failing again when it tries to interpret importing our App.css file. Considering unit tests don’t rely too much on the how the DOM looks when rendered, we’re going to use a module which handles this within our jest.config.ts in moduleNameMapper.

Adding identity-obj-proxy to our project

This module (identity-obj-proxy) essentially is for testing imports that may not affect your unit tests.

Next we’ll just modify our jest.config.ts file.

jest.config.ts

If we see our yarn test, we’ll notice another error:

$ jest
FAIL src/__tests__/App.test.tsx
✕ Renders main page correctly (1 ms)
● Renders main page correctlyThe 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
8 | test('Renders main page correctly', () => {
9 | // Setup
> 10 | render(<App />);
| ^

This is because we haven’t configured Jest to run tests for with a browser environment in mind. To fix this, we’ll just add a new attribute called testEnvironment and set it to jsdom.

jest.config.ts

Our tests should be running fine now for rendering things, but now we need to test interactions.

Testing State & Interactions

The main interaction we’re going to test is a click event when the user clicks the button and verify that the state has changed.

I like to structure my tests with everything that needs to be setup, pre expectations before any interactions, the desired action performed, and then any post expectations to cover the full scenario as much as possible.

src/__tests__/App.test.jsx

Running yarn test should give a pass.

❯ yarn test
yarn run v1.22.10
$ jest
PASS src/__tests__/App.test.tsx
✓ Renders main page correctly (68 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.708 s, estimated 3 s
Ran all test suites.
✨ Done in 6.12s.

Next, we’re going to simulate two click events using the @testing-library/user-event library.

src/__tests__/App.test.jsx

Extending Jest Further

Now that we have our tests fully working, we might want our test scenarios to be a bit clearer, but creating an element that only appears when the count is greater than 0. We could just identify this by querying the DOM if an element is null, but we’re going to extend things to be clearer using @testing-library/jest-dom. The only issue with this module is that we would need to import it with every test we make, so instead we’re going to import it for all our tests using jest.setup.ts.

Adding @testing-library/jest-dom

We’ll need to create a new jest.setup.ts file which we’ll reference in our jest.config.ts.

jest.setup.ts

In our jest.config.ts we’ll reference it by using setupFilesAfterEnv.

jest.config.ts

Now we’ll create a new code tag in our App.tsx file that shows on the condition that count is greater than zero.

src/App.tsx

Revising our test we can now see that we use a clearer test called .toBeInTheDocument().

src/__tests__/App.test.tsx

You can definitely add more, but if you’re looking for a quick setup for Jest, then this is a good base to start with.

Where To Go From Here?

The next step for this would be to start adding more tests, and potentially work towards route changes with react-router-dom. I am going to be working on a more detailed article to cover Metamask unit tests with Jest and then also cover E2E tests with Cypress. That is coming, but as you can imagine, writing tests for tests and explaining tests can take some time.

If you got value from this, please also follow me on twitter (where I’m quite active) @codingwithmanny and instagram at @codingwithmanny.

You can also find me on the Developer DAO Discord as codingwithmanny :).

Other Articles I’ve Written:

--

--

Manny

DevRel Engineer @ Berachain | Prev Polygon | Ankr & Web Application / Full Stack Developer