Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
ExpressJS API endpoint promises timing out with Sinon unit tests

I am trying to test some API endpoints without actually hitting the database (happens when using supertest). So I am trying to stub/fake the routes and just force a return. The other issue is if I wanted to mock the internal methods that are in the routes, I am having problems doing that as well.

The API is structured like this:

controller.js

export const route = "/named-route";
export const controller = new Router();

controller.get("/:id", async (req, res, next) => {
  try {
    const post = await getPost(req);
    res.status(200).json(post);
  } catch (err) {
    next(err);
  }
});

router.js

import {
  controller as myController,
  route as myRoute
} from "./controller.js";
router.use(myRoute, myController);
const router = Router();
export default router;

app.js

import router from "./router.js";
const app = express();
app.use(router);
export default app;

My testing attempts

import { expect } from "chai";
import sinon from "sinon";
import request from "supertest";
import app from "./app.js";
import { controller } from "./controller.js";

describe("my controller", function () {
  describe("GET", function () {
    it("tries to get a post", async function () {
      // attempt 1 -- times out
      const controllerStub = sinon.stub(controller, "get").resolves({..json});
      await request(controllerStub)
        .get("/named-route")
        .then(async (res) => {
          sinon.assert.match(res.body.statusCode, 200);
        });

      // attempt 2 -- times out
      const controllerStub = sinon.stub(controller, "get").callsFake(
        async () => new Promise((resolve) => {
          resolve({statusCode: 200})
        });
      );
      // same test call as above

      // works but hits actual DB, problematic for POST type requests
      const response = await request(app)
        .get("/named-route");
      expect(response.statusCode).to.equal(200);
    });
  });
});
about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!