Step 12: Refactor
So far, we used Postman to inspect the behavior of our API server. In particular, when we refactored the API or added a new feature, we tried a few endpoints to ensure the changes did not break the API. Unfortunately, this approach to testing is not comprehensive enough. Ideally, you have a complete suite of tests covering all API specifications. To that aim, we will first refactor the API server to access the express app
without binding it to a port. We require this change to run and test the app without running the server!
Add an index.js
file to the src
folder with the following content:
import express from "express";
import bookmarks from "./routes/bookmarks.js";
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.send("Welcome to the Bookmark API!");
});
app.use(bookmarks);
export default app;
Next, overwrite the server.js
to contain only the following content:
import app from "./src/index.js";
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Bookmark API at http://localhost:${PORT}/`);
});
Save and commit changes. Moreover, run the server and try the API in Postman to ensure it works as expected.