AceDevHub
Advanced Node.js Interview QuestionsAdvancedPractical

Node.js · Question 81

How do you test Node.js applications with Jest?

Direct answer

Jest runs unit and integration tests — describe/it, expect matchers, mock modules with jest.mock, test async with async/await; use supertest or inject() for HTTP; separate test DB; run in CI with NODE_ENV=test.

Testing Node services focuses on pure functions, handlers, and repositories — mock external I/O (pg, Redis, fetch) for fast unit tests; integration tests hit real Docker Postgres on port 5433.

LayerWhat to testTool
UnitService logic, mappersJest + mocks
HTTPRoute status/bodyFastify inject() or supertest
IntegrationSQL repositoriesTest DB + transactions rollback
E2EFull flowsSeparate suite; slower CI job
  • jest.mock('pg') — stub pool.query return values.
  • beforeEach/afterAll — reset mocks; close server and pool.
  • Coverage — CI gate on critical modules; not 100% everywhere.
jest-test.mjs
import { describe, it, expect, jest } from "@jest/globals";

describe("interviewsService", () => {
  it("returns topic page for valid slug", async () => {
    jest.spyOn(repo, "findTopicBySlug").mockResolvedValue({ slug: "nodejs-interview-questions" });

    const result = await service.getTopicPage("nodejs-interview-questions");
    expect(result.slug).toBe("nodejs-interview-questions");
  });
});

// HTTP: const res = await app.inject({ method: "GET", url: "/health" });