🟢 Node.js Intermediate

How do you write unit tests for Node.js applications?

Answer

Testing Node.js applications involves three main levels: unit (test individual functions in isolation), integration (test multiple components together), and end-to-end (test the full application). Popular testing frameworks: (1) Jest — all-in-one framework by Meta: test runner, assertion library, mocking: test("adds numbers", () => { expect(add(2, 3)).toBe(5); });; (2) Mocha + Chai — flexible test runner with separate assertion library; (3) Vitest — Jest-compatible, faster, ESM-native. For HTTP endpoint testing: Supertest — makes HTTP requests against Express apps without a running server: const res = await request(app).post("/users").send(data).expect(201);. For mocking: jest.fn() for function mocks, jest.spyOn() to spy on methods, jest.mock("module") to mock entire modules. Key practices: test one thing per test, use descriptive test names, arrange-act-assert structure, avoid testing implementation details — test behavior. Run with npm test. Aim for high coverage on business logic, less on boilerplate.