API Testing with Supertest
Guide
Check those videos. First one is related to supertest, other one is really important
as your properly working test would manipulate the filesystem so you would need
to set up a mock database.
Testing Node Server with Jest and Supertest
Learn how to test a node.js HTTP server using Jest and
Supertest.
https://www.youtube.com/watch?v=FKnzS_icp20
Mocking a Database in Node with Jest
Learn how to use jest mock functions to mock a database in an
HTTP server.
https://www.youtube.com/watch?v=IDjF6-s1hGk
npm install --save-dev jest supertest
Open the package.json and add the code below to it.
"jest": {
"testEnvironment": "node",
"coveragePathIgnorePatterns": [
"/node_modules/"
]
},
API Testing with Supertest Guide 1
Next up we add the test script. Inside the scripts portion of the package.json , add
the script below:
"test": "jest"
app.js
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
app.use(express.json());
app.get("/", function (req, res) {
res.send("Hello World");
});
app.post("/posts", (req, res) => {
const { title, content } = req.body;
const postFileName = `${title}.txt`;
const postFilePath = path.join(__dirname, postFileName);
const isPostExist = fs.existsSync(postFilePath);
if (isPostExist) {
res.status(409).send("Post already exists!");
}
if (title && content) {
try {
fs.writeFileSync(postFilePath, content);
res
.status(201)
.header("Content-Type", "text/plain")
.send("Post created successfully");
API Testing with Supertest Guide 2
} catch (error) {
res.status(500).send(`Internal server error: ${error}`);
}
} else {
res.status(400).end("Please provide a title and a content!")
}
});
app.get("/posts/:title", (req, res) => {
const title = req.params.title;
const postFileName = `${title}.txt`;
const postFilePath = path.join(__dirname, postFileName);
const isPostExist = fs.existsSync(postFilePath);
if (isPostExist) {
try {
const postContent = fs.readFileSync(postFileName, "utf-8")
res.status(200).send(postContent);
} catch (error) {
res.status(500).send(`Internal server error: ${error}`);
}
} else {
res.status(404).end("Post does not exist!");
}
});
app.patch("/posts/:title", (req, res) => {
const title = req.params.title;
const content = req.body.content;
const postFileName = `${title}.txt`;
const postFilePath = path.join(__dirname, postFileName);
const isPostExist = fs.existsSync(postFilePath);
if (isPostExist) {
try {
const postContent = fs.writeFileSync(postFilePath, content
API Testing with Supertest Guide 3
res.status(200).send("Post updated successfully");
} catch (error) {
res.status(500).send(`Internal server error: ${error}`);
}
} else {
res.status(404).end("Post does not exist!");
}
});
app.delete("/posts/:title", (req, res) => {
const title = req.params.title;
const postFileName = `${title}.txt`;
const postFilePath = path.join(__dirname, postFileName);
const isPostExist = fs.existsSync(postFilePath);
if (isPostExist) {
try {
const postContent = fs.unlinkSync(postFileName);
res.status(200).send("Post deleted successfully");
} catch (error) {
res.status(500).send(`Internal server error: ${error}`);
}
} else {
res.status(404).end("Post does not exist!");
}
});
app.get("/posts", (req, res) => {
try {
const files = fs.readdirSync(__dirname);
const postFiles = files.filter((file) => path.extname(file)
const fileContents = [];
postFiles.forEach((file) => {
try {
const postFilePath = path.join(__dirname, file);
API Testing with Supertest Guide 4
const data = fs.readFileSync(postFilePath, "utf-8");
fileContents.push({ fileName: file, content: data });
} catch (error) {
res.status(500).send(`Error reading file: ${error}`);
}
});
res.status(200).send(fileContents);
} catch (error) {
res.status(500).send(`Error reading directory: ${error}`);
}
});
module.exports = app;
server.js
const app = require("./app");
app.listen(3000, () => console.log("Server listening on port loc
app.test.js
const request = require("supertest");
const app = require("./app.js");
describe("POST /posts", () => {
describe("given a new blog post title and content", () => {
it("should respond with a 201 status code", (done) => {
request(app)
.post("/posts")
.send({ title: "title", content: "random content" })
.expect(201)
.end(done);
});
it("should respond with content-type text/plain", (done) =>
API Testing with Supertest Guide 5
request(app)
.post("/posts")
.send({ title: "title", content: "random content" })
.expect("Content-Type", "text/plain; charset=utf-8")
.end(done);
});
});
describe("given only content", () => {
it("should respond with a 400 status code", (done) => {
request(app)
.post("/posts")
.send({ content: "random content" })
.expect(400)
.end(done);
});
});
});
command to run the test
npm test
API Testing with Supertest Guide 6