Node.js Testing Interview Questions Jest, Supertest, and Testing Best Practices
Master Node.js testing interview questions unit tests, integration tests, mocking, test coverage, and testing best practices.
Node.js Testing Interview Questions
Testing is essential for production applications. Here are the most common interview questions.
Q1: What Are the Types of Tests?
Answer:
- Unit tests Test individual functions in isolation
- Integration tests Test how components work together
- End-to-end (E2E) tests Test the full application flow
- Performance tests Test speed and scalability
- Security tests Test for vulnerabilities
Q2: How Do You Test Express APIs?
Answer: Use Jest + Supertest:
const request = require("supertest"); const app = require("../src/app"); describe("POST /api/signup", () => { it("should create a new user", async () => { const res = await request(app) .post("/api/signup") .send({ firstName: "John", email: "[email protected]", password: "Test@1234" }); expect(res.status).toBe(201); expect(res.body.data).toHaveProperty("_id"); expect(res.headers["set-cookie"]).toBeDefined(); }); it("should return 400 for missing fields", async () => { const res = await request(app) .post("/api/signup") .send({ email: "[email protected]" }); expect(res.status).toBe(400); }); });
Q3: How Do You Test with a Database?
Answer: Use mongodb-memory-server:
const { MongoMemoryServer } = require("mongodb-memory-server"); let mongoServer; beforeAll(async () => { mongoServer = await MongoMemoryServer.create(); await mongoose.connect(mongoServer.getUri()); }); afterEach(async () => { // Clean up collections between tests await User.deleteMany({}); }); afterAll(async () => { await mongoose.disconnect(); await mongoServer.stop(); });
Q4: How Do You Mock Functions?
Answer:
// Mock a module jest.mock("../src/utils/emailService"); const { sendEmail } = require("../src/utils/emailService"); sendEmail.mockResolvedValue({ success: true }); // Mock a Mongoose model method jest.mock("../src/models/User"); User.findById.mockResolvedValue({ _id: "123", name: "John" }); // Spy on a function const spy = jest.spyOn(console, "log"); // ... run code ... expect(spy).toHaveBeenCalledWith("Hello"); spy.mockRestore();
Q5: What Is Test Coverage?
Answer: Coverage measures what percentage of your code is tested:
# Run with coverage jest --coverage
Metrics:
- Line coverage % of lines executed
- Branch coverage % of if/else branches tested
- Function coverage % of functions called
- Statement coverage % of statements executed
Aim for 80%+ coverage, but focus on critical paths.
Q6: How Do You Test Async Code?
Answer:
// async/await test("should fetch user", async () => { const user = await User.findById("123"); expect(user.name).toBe("John"); }); // Resolves/rejects test("should resolve", () => { return expect(Promise.resolve("ok")).resolves.toBe("ok"); }); test("should reject", () => { return expect(Promise.reject(new Error("fail"))).rejects.toThrow("fail"); });
Q7: What Should You Test?
Answer:
- Happy path Normal successful operation
- Edge cases Empty input, boundary values
- Error cases Invalid input, not found, unauthorized
- Side effects Database changes, emails sent
- Security Unauthenticated access, authorization
The Takeaway
Testing interview questions cover: test types (unit, integration, E2E, performance, security), testing Express APIs (Jest + Supertest), database testing (mongodb-memory-server for isolated tests), mocking (jest.mock for modules, jest.spyOn for spies), test coverage (line, branch, function, statement aim 80%+), async testing (async/await, resolves/rejects), and what to test (happy path, edge cases, errors, side effects, security).
Unit tests (individual functions in isolation), integration tests (components working together), end-to-end tests (full application flow), performance tests (speed and scalability), and security tests (vulnerabilities). Unit tests are fast and numerous, E2E tests are slow and few.
Use Jest as the test runner and Supertest for HTTP requests. Import the Express app, use request(app).post('/api/signup').send({...}), and assert on the response status, body, and headers. Supertest doesn't require the server to be running it calls the Express app directly.
Use mongodb-memory-server to create an in-memory MongoDB instance. Connect in beforeAll, clean collections in afterEach (deleteMany({})), and disconnect in afterAll. This ensures tests are isolated, fast, and don't affect your development database.
Coverage measures what percentage of code is tested (line, branch, function, statement). Run with jest --coverage. Aim for 80%+ overall, but focus on critical paths. 100% coverage doesn't mean bug-free focus on meaningful tests, not just coverage numbers.
Use jest.mock('../module') to replace a module with a mock, then use mockResolvedValue or mockImplementation to control the return. Use jest.spyOn(object, 'method') to spy on existing functions. Use mockRestore() to restore the original.
Ready to master Node.js completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master Node.js
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

