Introduction
Typescript is a superset of JavaScript that adds optional static typing to the language. It is designed to make large-scale JavaScript applications more manageable and easier to maintain. React is a popular JavaScript library for building user interfaces. Jest is a testing framework that makes it easy to write and run tests for your JavaScript code.
In this guide, we will walk you through the process of setting up a Typescript, React, and Jest project from scratch. We will cover everything from installing the necessary packages to writing tests for your code.
Prerequisites
Before we get started, you should have some basic knowledge of JavaScript, React, and Node.js. You should also have Node.js and npm installed on your machine.
Setting up the Project
To get started, create a new directory for your project and navigate into it:
mkdir my-app
cd my-app
Next, initialize a new Node.js project:
npm init -y
This will create a new package.json
file in your project directory.
Installing Dependencies
To use Typescript with React, you will need to install the following packages:
npm install --save-dev typescript @types/react @types/react-dom
This will install Typescript and the necessary type definitions for React and ReactDOM.
Next, install Jest:
npm install --save-dev jest @types/jest ts-jest
This will install Jest and the necessary type definitions for it. We are also installing ts-jest
, which is a package that allows Jest to work with Typescript.
Configuring Jest
To configure Jest, create a new file called jest.config.js
in the root of your project directory:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
This tells Jest to use ts-jest
as its preset and to run tests in a Node.js environment.
Configuring Typescript
To configure Typescript, create a new file called tsconfig.json
in the root of your project directory:
{
"compilerOptions": {
"jsx": "react",
"esModuleInterop": true,
"lib": ["dom", "es2015"],
"module": "commonjs",
"moduleResolution": "node",
"noImplicitAny": true,
"outDir": "./dist",
"sourceMap": true,
"target": "es5"
},
"include": ["./src/**/*"]
}
This tells Typescript to compile our code into ES5 syntax and output it to the dist
directory. It also tells Typescript to use the dom
and es2015
libraries, which are required by React.
Writing Code
Now that we have our project set up, let’s start writing some code! Create a new file called index.tsx
in the src
directory:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
const App = () => {
return (
<div>
<h1>Hello World!</h1>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
This is a simple React component that renders an <h1>
element with the text “Hello World!”.
Running Tests
Now that we have some code written, let’s write some tests for it! Create a new file called index.test.tsx
in the src
directory:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import App from './index';
let container: HTMLDivElement;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container.remove();
});
it('renders with or without a name', () => {
act(() => {
ReactDOM.render(<App />, container);
});
expect(container.textContent).toBe('Hello World!');
});
This test uses Jest’s built-in test runner to render our <App>
component and check that it renders an <h1>
element with the text “Hello World!”.
To run our tests, use the command npm test
.
SVG Image Handling in Jest
Jest does not know how to load other file extensions than js/jsx by default. Therefore, you need to find the jest.config.js file and add transformer for svg files.
"transform": {
"^.+\\\\.tsx?$": \"ts-jest\",
\"^.+\\\\.svg$\": \"<rootDir>/svgTransform.js\"
},
Create svgTransform.js file in your root directory with the following content
Handling ESM modules in Jest:
Sure, if you’re using TypeScript with ts-jest in your project, you can adjust your Jest configuration as follows:
module.exports = {
// ...
preset: 'ts-jest',
testEnvironment: 'node',
transformIgnorePatterns: [
"/node_modules/(?!your-esm-module)"
],
// ...
};
In this configuration, preset: 'ts-jest'
tells Jest to use ts-jest for transpiling your TypeScript code. The testEnvironment: 'node'
option specifies that the test environment that will be used for testing is Node.js.
The transformIgnorePatterns
option works the same way as in the previous example. It tells Jest to ignore transformations for the specified ESM modules.
Remember to replace your-esm-module
with the actual name of your ESM module. If you have multiple ESM modules, you can add them in the pattern separated by a |
, like so: "/node_modules/(?!esm-module-1|esm-module-2)"
.
Remember to install babel-jest
and @babel/preset-env
, and also create a .babelrc
file in your project root with the following content if you haven’t done so:
{
"presets": ["@babel/preset-env"]
}