fix: avoid starting backend server during tests#258
Conversation
Signed-off-by: pggdev <princegupta.ns153@gmail.com>
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
There was a problem hiding this comment.
Code Review
This pull request refactors the server startup logic in backend/src/server.js by encapsulating it within an exported startServer function and implementing a main module guard for direct execution. The review feedback suggests adopting the node: prefix for built-in module imports and using realpathSync to ensure the main module check is robust against symbolic links.
| @@ -1,5 +1,6 @@ | |||
| import express from "express"; | |||
| import cors from "cors"; | |||
| import { pathToFileURL } from "url"; | |||
There was a problem hiding this comment.
In ECMAScript Modules (ESM), it is a best practice to use the node: prefix when importing built-in Node.js modules (e.g., node:url) to clearly distinguish them from npm packages. Additionally, I've included realpathSync from node:fs to support a more robust main module check in the direct-run guard.
import { pathToFileURL } from "node:url";
import { realpathSync } from "node:fs";| if ( | ||
| process.argv[1] && | ||
| import.meta.url === pathToFileURL(process.argv[1]).href | ||
| ) { | ||
| startServer(); | ||
| } |
There was a problem hiding this comment.
The current check for the main module using process.argv[1] can be brittle. import.meta.url always contains the fully resolved path (with symbolic links resolved), whereas process.argv[1] might contain a symbolic link path depending on how the script was invoked. Using realpathSync ensures both paths are fully resolved before comparison, making the guard more robust across different deployment and execution environments.
| if ( | |
| process.argv[1] && | |
| import.meta.url === pathToFileURL(process.argv[1]).href | |
| ) { | |
| startServer(); | |
| } | |
| if ( | |
| process.argv[1] && | |
| import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href | |
| ) { | |
| startServer(); | |
| } |
Description
#257
Updated the backend startup logic so importing
appfromserver.jsdoes not start the HTTP server.Changes
app.listen(...)into an exportedstartServerfunctionserver.jsis executed directlyappimportable for Supertest without opening port3001Testing
npm run test -- --run