Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Getting started with Typescript, React and Jest

Getting Started

  1. Install:
  • jest: npm install --save-dev jest
  • ts-jest: npm install --save-dev ts-jest @types/jest
  1. Modify package.json
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
    "moduleFileExtensions": [
  "scripts": {
    "test": "jest"
  1. Running tests npm test

  2. Ensuring tests are excluded from webpack

Modify webpack.config.js

{ test: /\.tsx?$/, exclude: /\.test.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },

Writing the Tests

Test Setup

modify package.json to the appropriate location of your setup file eg. ClientApp/setupTests.ts

"jest": {
    "setupTestFrameworkScriptFile": "<rootDir>/ClientApp/setupTests.ts",

Snapshot tests

i. Install react-test-renderer

npm install --save-dev react-test-renderer @types/react-test-renderer

ii. Write your tests!

import * as React from "react";
import * as renderer from "react-test-renderer";
import { SubjectToBeTested } from "./SubjectToBeTested";

it("SubjectToBeTested renders correctly", () => {
  const props = { className: "test", value: true, onSelectChanged: (value: boolean) => { return; } };
  const tree = renderer
    .create(<SubjectToBeTested {...props} />)

DOM tests

i. Install Enzyme:

npm install --save-dev enzyme @types/enzyme
npm install --save-dev enzyme-adapter-react-16 @types/enzyme-adapter-react-16

ii. Modify setupTests.ts

import { configure } from "enzyme";
import React16Adapter from "enzyme-adapter-react-16";

configure({ adapter: new React16Adapter() });

iii. Write your tests!

import {shallow} from "enzyme";
import * as React from "react";
import { SubjectToBeTested } from "./SubjectToBeTested";

it("SubjectToBeTested calls onSelectChanged", () => {
  let newValue = false;
  const props = { className: "test", value: true, onSelectChanged: (value: boolean) => { newValue = value; } };
  const sut = shallow(<SubjectToBeTested {...props} />);

  sut.find("select").simulate("change", {target: { value : "true"}});
  sut.find("select").simulate("change", {target: { value : "false"}});

Configuring for VSTS

  1. Install jest-junit: npm install --save-dev jest-junit
  2. Update Jest config package.json
 "jest": {
    "testResultsProcessor": "jest-junit",
  1. Ensure junit.xml is excluded via .gitignore ;)
  2. Add npm task to the build
  • Command: custom
  • Command and arguments: test
  1. Add Publish Results task to the build
  • Test result format: JUnit
  • Test result files: **/junit.xml


  • Problems with imports? Try "allowSyntheticDefaultImports": true, in tsconfig.json
  • DevDependency grief? Try "no-implicit-dependencies": [true, "dev"], in tslint.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment