Initial Setup with Jest & TypeScript [JavaScript]


Jest is JavaScript test framework which is less configuration.

This article describes how to setup Jest with TypeScript.

🎳 Install libraries

yarn add --dev jest ts-jest @types/jest

🏀 Configure Jest

Modify package.json to add run test configuration.
(If you want to run test sequentially, please use jest --runInBand.)

"scripts": {
"test": "jest"
}

Create jest.config.js file for configuring Jest.

module.exports = {
moduleFileExtensions: ["ts", "tsx", "js", "json"],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest"
},
globals: {
"ts-jest": {
tsConfigFile: "tsconfig.json"
}
},
testMatch: ["**/__tests__/specs/**/*.+(ts|tsx|js)"],
testPathIgnorePatterns: ["/node_modules/", "/dist/", "/lib/"],
setupTestFrameworkScriptFile: "./__tests__/setup.ts",
verbose: true,
testURL: "http://localhost/"
};

🐰 Setup for all test

Create ./__tests__/setup.ts file for putting common configuration.
(e.g. clean up after all tests have run or setuping/closing DB)

// Example
import { getConnection, getConnectionManager } from "typeorm";

beforeAll(async () => {
const connectionManager = getConnectionManager();
const connection = connectionManager.create({ /* test configuration */ });
await connection.connect();
});

afterAll(async () => {
await getConnection().close();
});

🎂 Write tests

Create a ./src/sum.ts function file.

const sum = (a, b) => {
return a + b;
};
module.exports = sum;

After create a file which you want to write test, add ./__tests__/specs/sum.ts test file.

import { sum } from "../../../src/sum.ts";

test("adds 1 + 2 to equal 3", () => {
expect(sum(1, 2)).toBe(3);
});

Run the test.

yarn test
# PASS ./sum.test.js
# ✓ adds 1 + 2 to equal 3 (5ms)

👽 [Appendix] Unit test with supertest

supertest suports unit test for Express.js App.

Installation

yarn add supertest # npm install supertest --save-dev

How to use

import * as request from "supertest";
import * as express from "express";

const app = express();

app
.get("/user", function(req, res) {
res.status(200).json({ name: "john" });
})
.post("/users", function(req, res) {
res.status(200).json({ status: "create user!" });
});

describe("GET /user", () => {
it("respond with json", done => {
request(app)
.get("/user")
.set("Accept", "application/json")
.expect("Content-Type", /json/)
.expect(200, done);
});
});

describe("POST /users", () => {
it("responds with json", done => {
request(app)
.post("/users")
.send({ name: "john" })
.set("Accept", "application/json")
.expect(200)
.end(function(err, res) {
if (err) return done(err);
done();
});
});
});

If I want to use create sample data, I needs to write the following things:

let user;

before(async () => {
user = await createUser();
})

🐝 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!