Step 4
Let's explore the test script:
const supertest = require("supertest");
const app = require("../server");
const request = supertest(app);
test("Get 200 for API homepage", async () => {
const response = await request.get("/");
expect(response.status).toBe(200);
});
We use supertest
to wrap the express app
. It allows us to send a request to the API without actually running the server.
const supertest = require("supertest");
const app = require("../server");
const request = supertest(app);
request
.get("/")
.then((response) => {
console.log(response.status); // HTTP status code sent by the server
console.log(response.body); // The response body sent by the server
})
.catch((err) => console.log(err));
All you need in a test file is the test
function which runs a test. The first argument is the test name; the second argument is a function that contains the expectations to test.
test("two plus two is four", () => {
expect(2 + 2).toBe(4);
});
This test used expect
and toBe
to test that two values were identical.
Resources
- Consult the examples posted on SuperTest repository for its API.
- To learn about the things that Jest can test, see Using Matchers.