Skip to content

Testing and Debugging Interview Questions for Full Stack with Node.js

22 Testing and Debugging questions with answers for full stack with node.js roles — 7 easy, 8 medium, 7 hard.

About Testing and Debugging

Write unit and integration tests with Jest, Supertest and the built-in node test runner, mock dependencies and run tests against real databases in CI. Debug with the inspector, profile CPU and memory, add structured logging with correlation IDs, handle flaky tests, and learn contract testing and load testing before high-traffic events.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the difference between unit, integration and end-to-end tests for a Node.js API?

Save to ▾
Show answer
Unit tests check a single function or service in isolation with dependencies mocked; they are fast and numerous. Integration tests check several parts together, such as a route, service and a real test database. End-to-end tests run the full system like a user would, often through HTTP against a deployed environment. A healthy test pyramid has many unit tests and fewer E2E tests.
02

Write a Jest unit test for a function that calculates order total with GST.

Save to ▾
Show answer
// pricing.js const total = (items, gst = 0.18) => Math.round(items.reduce((s, i) => s + i.price * i.qty, 0) * (1 + gst) * 100) / 100; module.exports = { total }; // pricing.test.js const { total } = require('./pricing'); describe('total', () => { it('adds 18% GST by default', () => { expect(total([{ price: 100, qty: 2 }])).toBe(236); }); it('returns 0 for an empty cart', () => { expect(total([])).toBe(0); }); });
03

How do you debug a Node.js application?

Save to ▾
Show answer
Start Node with --inspect or --inspect-brk and attach Chrome DevTools at chrome://inspect or the VS Code debugger to set breakpoints, step through code and inspect variables. Use structured logs with request IDs to trace issues in deployed environments. For async issues, check stack traces with async context, and for performance use --cpu-prof or clinic.js flame graphs.
04

Why is structured logging important and which libraries are used?

Save to ▾
Show answer
Structured logs are JSON lines with fields like level, timestamp, requestId, userId and message, so tools like ELK, Loki, Datadog or CloudWatch can search and aggregate them. pino is fast and popular, winston is flexible with many transports. Log at correct levels, include a correlation ID per request, and never log passwords, tokens, full card numbers or Aadhaar numbers.
05

What is code coverage and is 100 percent coverage a good goal?

Save to ▾
Show answer
Code coverage measures how much code tests execute: lines, branches, functions and statements, reported by Jest with --coverage or c8. It shows untested areas but not whether assertions are meaningful. Chasing 100 percent leads to brittle tests of trivial code. A practical target is around 70 to 85 percent with strong coverage of business logic, error paths and security checks.
06

A new developer pushes code that breaks the login API in staging. How would you prevent this in future?

Save to ▾
Show answer
Add automated checks before merge: unit and integration tests for login in the CI pipeline, branch protection requiring green builds and at least one review, linting and type checks. Add a smoke test that runs after each staging deploy and alerts on failure. Treat it as a blameless learning moment and pair with the developer to write the missing tests.
07

How do you handle a situation where you cannot find the root cause of a bug before a deadline?

Save to ▾
Show answer
I inform my lead early with what I know, what I have ruled out and the risk. I propose a safe mitigation, such as a feature flag to disable the path or a rollback, and add extra logging to capture more data. In one case this let us release on time with the feature off, and the new logs revealed the cause two days later.
08

How do you test Express routes with Supertest?

Save to ▾
Show answer
const request = require('supertest'); const app = require('../app'); // export app without calling listen describe('GET /api/v1/users/:id', () => { it('returns 404 for an unknown user', async () => { const res = await request(app) .get('/api/v1/users/000000000000000000000000') .set('Authorization', `Bearer ${testToken}`); expect(res.status).toBe(404); expect(res.body.error).toBeDefined(); }); });
09

How do you mock a database or external service in Jest?

Save to ▾
Show answer
// order.service.test.js jest.mock('../repositories/orderRepo'); const repo = require('../repositories/orderRepo'); const { cancelOrder } = require('../services/order.service'); test('cannot cancel a shipped order', async () => { repo.findById.mockResolvedValue({ id: 1, status: 'shipped' }); await expect(cancelOrder(1)).rejects.toThrow('Cannot cancel'); expect(repo.update).not.toHaveBeenCalled(); }); // For HTTP calls, nock or msw can intercept requests.
10

What is the built-in node:test runner and when would you use it over Jest?

Save to ▾
Show answer
Node.js ships a stable test runner in the node:test module with describe, it, mocks, coverage and watch mode, run with node --test. It needs no extra dependency and works natively with ES modules, which Jest still handles with extra configuration. Jest or Vitest offer richer snapshot testing, mocking and ecosystem. For small libraries or ESM-first services, node:test is a lightweight choice.
11

How do you run integration tests against a real database in CI?

Save to ▾
Show answer
Start a disposable database for the test run, using Docker Compose services in CI, Testcontainers from the test code, or mongodb-memory-server for MongoDB. Run migrations before tests, seed minimal data per test, and clean tables between tests or wrap each test in a rolled-back transaction. Use a separate DATABASE_URL so tests can never touch production data.
12

A test passes locally but fails randomly in CI. How do you approach this flaky test?

Save to ▾
Show answer
Run it repeatedly to reproduce, then look for shared state between tests, missing awaits, reliance on test order, real timers, current date or time zones, random data and network calls. Fix by isolating data per test, using fake timers, freezing dates, mocking external calls and awaiting all promises. Quarantine the test only temporarily with a ticket, never delete it silently.
13

How would you test code that depends on the current time, like an expiring coupon?

Save to ▾
Show answer
Inject a clock function instead of calling Date.now directly, or use Jest fake timers: jest.useFakeTimers().setSystemTime(new Date('2026-01-01')). Then test before, exactly at and after expiry. Store dates in UTC and convert for display in IST, which avoids bugs near midnight. Reset timers after each test with jest.useRealTimers to avoid leaking into other tests.
14

Tell me about a production incident you handled and what you did after it.

Save to ▾
Show answer
Situation: our payment callback endpoint started failing after a deploy on a Friday evening. Task: I was on call. Action: I checked error logs, saw a missing environment variable, rolled back within ten minutes, then added startup config validation and a post-deploy smoke test. Result: impact was limited to a few failed callbacks we replayed, and I wrote a blameless postmortem the team used to improve deploy checks.
15

Describe how you would mentor a junior developer who writes no tests.

Save to ▾
Show answer
I would start by understanding why: lack of time, knowledge or examples. Then I pair with them on one feature, writing a test first for a real bug so they see the value. I share a small template for service and route tests, review their tests kindly in pull requests and celebrate when a test catches a regression. Over a few sprints, testing becomes a habit.
16

How do you add a correlation ID to every log line for a request?

Save to ▾
Show answer
const { AsyncLocalStorage } = require('async_hooks'); const { randomUUID } = require('crypto'); const als = new AsyncLocalStorage(); app.use((req, res, next) => { const id = req.get('X-Request-Id') || randomUUID(); res.set('X-Request-Id', id); als.run({ requestId: id }, next); }); const log = (msg, extra = {}) => logger.info({ ...extra, requestId: als.getStore()?.requestId }, msg); // Pass the ID to downstream services in headers.
17

Production shows intermittent 502 errors from the load balancer but your app logs show nothing. How do you investigate?

Save to ▾
Show answer
A 502 means the load balancer got a bad or no response from the app. Check whether pods restarted or crashed through OOM kills, health check failures and deployment times. A common Node cause is keep-alive mismatch: set server.keepAliveTimeout higher than the load balancer idle timeout and headersTimeout above that. Also check event loop blocking and connection limits.
18

How do you find which function is using the most CPU in a Node.js service?

Save to ▾
Show answer
Reproduce the load with autocannon or k6, then profile with node --cpu-prof to generate a .cpuprofile file and open it in Chrome DevTools, or use clinic flame to get a flame graph. Wide bars show hot functions. Common culprits are JSON.stringify on huge objects, synchronous crypto, regex backtracking and heavy loops. Fix and re-measure under the same load.
19

What is contract testing and why is it useful for microservices?

Save to ▾
Show answer
Contract testing verifies that a provider API and its consumers agree on request and response formats without running the whole system. With Pact, the consumer writes expectations that become a contract, and the provider runs them in its own CI. It catches breaking changes like a renamed field before deployment, and is faster and less flaky than full end-to-end environments.
20

How do you load test a Node.js API before a big sale event?

Save to ▾
Show answer
Define targets from expected traffic, such as 5,000 requests per second with p95 under 300 ms. Write realistic scenarios in k6 or Artillery covering browse, cart and checkout, run them against a production-like environment, and ramp up gradually. Watch latency, error rates, CPU, memory, event loop lag and database metrics, then fix bottlenecks and rerun until targets are met with headroom.
21

A regex in your validation code makes the server hang on certain inputs. What is the issue?

Save to ▾
Show answer
This is likely ReDoS, regular expression denial of service. Patterns with nested quantifiers such as (a+)+ can backtrack exponentially on crafted input, blocking the event loop. Fix by simplifying the regex, limiting input length before matching, using well-tested validators like validator.js, or a linear-time engine such as re2. Add tests with long malicious strings.
22

After a Node.js version upgrade, a few integration tests fail with date and crypto differences. How do you handle the upgrade safely?

Save to ▾
Show answer
Read the release notes and changelog for breaking changes, such as deprecated APIs, OpenSSL updates or changed default behaviour. Run the full test suite on the new version in a CI matrix alongside the old one, fix failures one by one and check native modules rebuild correctly. Roll out to staging, then to a canary in production while watching error rates before upgrading all services.

Frequently asked questions

How important is Testing and Debugging in Full Stack with Node.js interviews?

Write unit and integration tests with Jest, Supertest and the built-in node test runner, mock dependencies and run tests against real databases in CI. Debug with the inspector, profile CPU and memory, add structured logging with correlation IDs, handle flaky tests, and learn contract testing and load testing before high-traffic events.

How should I use the Testing and Debugging sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.