API tests with jest and typescript
I want to test my typescript API using tests written in typescript (obviously). Jest doesn't support typescript out of the box and there are several possible solutions, but the easiest and more straightforward way is by using ts-jests
Setup ts-jests #
First install the dependencies:
npm i -D jest typescript ts-jest @types/jest
npx ts-jest config:init
And create a jest config file:
npx ts-jest config:init
It creates this simple jest config file:
jest.config.js
:
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
};
Test folder location #
The tests must be located in a place Typescript find them. If they are not inside src/
folder, probably you have to add the test folder to the tsconfig.
For example:
tsconfig.json
:
{
"compilerOptions": {
...
},
"include": ["src/**/*", "tests/**/*"]
}
Everything else works as expacted.
API testing with supertest #
Install library and types:
npm i -D supertest @types/supertest
Create your test:
tests/status.spec.ts
:
import request from "supertest";
import app from "../app";
describe("Status", () => {
test("It should return a valid response", async () => {
const response = await request(app).get("/status");
expect(response.status).toBe(200);
});
});
Or sending a POST request:
tests/authorization.spec.ts
:
import request from "supertest";
import app from "../src/app";
describe("Authorization", () => {
test("It should login with a user", async () => {
const response = await request(app)
.post("/v1/login")
.send({ email: "test@example.com", password: "secret" });
expect(response.status).toBe(200);
});
});