🟢 Node.js Intermediate

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

Why Interviewers Ask This

This question targets practical, hands-on experience with Node.js. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

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.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Node.js project.