Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda