InterviewTreedInterviewTreed

InterviewTreed Question Bank

Testing & Automation Interview Questions and Answers

Prepare for software testing and automation interviews, covering testing fundamentals, unit testing, integration testing, API automation, UI automation, test frameworks, mocking, CI/CD, and quality engineering.

Total Questions

75

Beginner

27

Intermediate

35

Advanced

13

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Testing Fundamentals

What is software testing?

Software testing evaluates whether a system behaves as expected and helps reveal defects, risks, and gaps in requirements.

Answer

Software testing evaluates whether a system behaves as expected and helps reveal defects, risks, and gaps in requirements. It includes verification of implementation and validation of user needs.

Syntax

test(input) -> actual result; compare with expected result

Example

For a tax calculator, test normal values, boundaries, invalid inputs, and rounding behavior.

Code example

expect(calculateTax(100)).toBe(10);

Diagram

Requirement -> test design -> execution -> result -> defect feedback

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q2Testing Fundamentals

What is the difference between verification and validation?

Verification asks whether the product was built according to specification; validation asks whether it solves the user's actual problem.

Answer

Verification asks whether the product was built according to specification; validation asks whether it solves the user's actual problem. Reviews and static checks support verification, while realistic execution and user acceptance support validation.

Syntax

Verification: build it right; validation: build the right thing

Example

Review a payment requirement for completeness, then test whether a customer can complete checkout successfully.

Code example

expect(checkout(total)).toMatchObject({ status: 'paid' });

Diagram

Specification review -> implementation checks; user scenario -> validation

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q3Testing Fundamentals

What is the testing pyramid?

The testing pyramid recommends many fast, focused unit tests, fewer integration tests, and a smaller set of end-to-end tests.

Answer

The testing pyramid recommends many fast, focused unit tests, fewer integration tests, and a smaller set of end-to-end tests. The exact balance depends on architecture, but tests should be reliable and provide fast feedback.

Syntax

Many unit tests > fewer integration tests > fewer E2E tests

Example

Test price calculations as units, repository queries as integration tests, and checkout as an E2E flow.

Code example

// Keep most business-rule tests isolated and fast

Diagram

          E2E
       Integration
    Unit tests (many)

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q4Testing Fundamentals

What is the difference between manual and automated testing?

Manual testing uses a person to execute and evaluate scenarios; automated testing uses scripts or tools to repeat checks.

Answer

Manual testing uses a person to execute and evaluate scenarios; automated testing uses scripts or tools to repeat checks. Automation is valuable for stable, repetitive regression coverage, while exploratory testing benefits from human judgment.

Syntax

test script -> repeatable assertions

Example

Automate login regression checks but use exploratory testing to investigate confusing new UX.

Code example

await page.getByRole('button', { name: 'Sign in' }).click();

Diagram

Tester/script -> application -> observed result

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q5Testing Fundamentals

What is a test case?

A test case describes preconditions, inputs, steps, and expected outcomes for a specific behavior.

Answer

A test case describes preconditions, inputs, steps, and expected outcomes for a specific behavior. Good cases are traceable to requirements and cover normal, boundary, and failure paths.

Syntax

Given preconditions, when action, then expected result

Example

Given a user with a valid account, when correct credentials are submitted, then the session is created.

Code example

expect(authenticate(validUser)).resolves.toHaveProperty('token');

Diagram

Precondition -> action -> assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q6Testing Fundamentals

What is a test suite?

A test suite groups related test cases, often around a module, feature, or risk.

Answer

A test suite groups related test cases, often around a module, feature, or risk. Suites should be organized so teams can run focused checks locally and broader suites in CI.

Syntax

describe('Users API', () => { ... })

Example

Keep all user-registration validation tests together under a Users API suite.

Code example

describe('Users', () => { it('rejects duplicate email', async () => { /* test */ }); });

Diagram

Test suite -> related test cases -> summary

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q7Testing Fundamentals

What is regression testing?

Regression testing checks that changes have not broken existing behavior.

Answer

Regression testing checks that changes have not broken existing behavior. A good regression suite prioritizes high-value user journeys, previously defective areas, and business-critical rules.

Syntax

change -> rerun relevant existing tests

Example

After changing discount logic, rerun pricing, checkout, refunds, and tax-related tests.

Code example

expect(calculateTotal(cart, coupon)).toBe(expectedTotal);

Diagram

Code change -> regression suite -> confidence

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q8Testing Fundamentals

What is smoke testing?

Smoke tests are a small set of high-level checks that determine whether a build is stable enough for deeper testing.

Answer

Smoke tests are a small set of high-level checks that determine whether a build is stable enough for deeper testing. They should be fast and cover critical functionality such as service startup and a key health endpoint.

Syntax

GET /health -> 200

Example

After deployment, verify health, authentication, and a basic read operation before running a full suite.

Code example

const response = await request(app).get('/health'); expect(response.status).toBe(200);

Diagram

Build/deploy -> smoke checks -> proceed or stop

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q9Testing Fundamentals

What is sanity testing?

Sanity testing is a focused check that a specific change or fix behaves as intended.

Answer

Sanity testing is a focused check that a specific change or fix behaves as intended. Teams sometimes use the term differently, so define its scope clearly in the team's process.

Syntax

targeted test around a recent fix

Example

After fixing password reset expiry, test valid, expired, and reused reset tokens.

Code example

expect(isResetTokenValid(expiredToken)).toBe(false);

Diagram

Targeted change -> focused checks -> result

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q10Testing Fundamentals

What is the difference between functional and non-functional testing?

Functional testing checks what a system does; non-functional testing checks qualities such as performance, reliability, accessibility, usability, and security.

Answer

Functional testing checks what a system does; non-functional testing checks qualities such as performance, reliability, accessibility, usability, and security. Both should be planned from requirements and risks.

Syntax

functional: expected response; non-functional: latency/security

Example

Check that search returns correct results and separately verify it meets a p95 latency target.

Code example

expect(response.body.items).toHaveLength(3);

Diagram

Feature behavior + quality attributes -> release evidence

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q11Testing Fundamentals

What is black-box testing?

Black-box testing evaluates externally observable behavior without relying on internal implementation details.

Answer

Black-box testing evaluates externally observable behavior without relying on internal implementation details. It is useful for API contracts, UI flows, and acceptance criteria.

Syntax

input -> system -> observable output

Example

Send valid and invalid JSON to an API and assert status codes and response schemas.

Code example

expect(response.status).toBe(400);

Diagram

Input -> opaque system -> output assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q13Testing Fundamentals

What is boundary value analysis?

Boundary value analysis focuses on values at and near the edges of valid ranges because defects often occur at boundaries.

Answer

Boundary value analysis focuses on values at and near the edges of valid ranges because defects often occur at boundaries. Test minimum, maximum, just below, and just above limits.

Syntax

min-1, min, min+1, max-1, max, max+1

Example

For an age range 18–65, test 17, 18, 19, 64, 65, and 66.

Code example

for (const age of [17, 18, 19, 64, 65, 66]) testAge(age);

Diagram

Valid range [min..max] -> test edge neighbors

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q14Testing Fundamentals

What is equivalence partitioning?

Equivalence partitioning divides inputs into groups expected to behave similarly, then selects representative values from each group.

Answer

Equivalence partitioning divides inputs into groups expected to behave similarly, then selects representative values from each group. It reduces redundant cases while preserving useful coverage.

Syntax

valid group; invalid groups

Example

For a quantity field, partitions may be positive integers, zero, negative values, decimals, and nonnumeric strings.

Code example

expect(validateQuantity(3)).toBe(true); expect(validateQuantity(-1)).toBe(false);

Diagram

Input domain -> partitions -> representative cases

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q21Unit Testing

What is unit testing?

Unit testing verifies a small unit such as a pure function or class in isolation from unrelated infrastructure.

Answer

Unit testing verifies a small unit such as a pure function or class in isolation from unrelated infrastructure. Tests should be fast, deterministic, and focused on public behavior.

Syntax

expect(add(2, 3)).toBe(5)

Example

Test a shipping-cost calculator without making network or database calls.

Code example

describe('shippingCost', () => { it('returns free shipping above threshold', () => expect(shippingCost(100)).toBe(0)); });

Diagram

Arrange -> Act -> Assert (isolated unit)

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q22Unit Testing

What are Arrange, Act, Assert?

Arrange, Act, Assert is a structure for tests: create the needed state, execute the behavior, and assert the outcome.

Answer

Arrange, Act, Assert is a structure for tests: create the needed state, execute the behavior, and assert the outcome. Clear phases make tests easier to read and diagnose.

Syntax

// Arrange; // Act; // Assert

Example

Arrange a user, call the service, then assert that the returned role is correct.

Code example

const user = makeUser(); const result = getDisplayName(user); expect(result).toBe('Ava');

Diagram

Arrange -> Act -> Assert

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q23Unit Testing

What is Jest?

Jest is a JavaScript/TypeScript testing framework with test discovery, assertions, mocks, setup hooks, and coverage reporting.

Answer

Jest is a JavaScript/TypeScript testing framework with test discovery, assertions, mocks, setup hooks, and coverage reporting. TypeScript projects may need a suitable transformer or a compatible runner configuration.

Syntax

npm test; jest --coverage

Example

Use Jest to test a pure utility and mock a collaborator where isolation is needed.

Code example

test('adds values', () => { expect(2 + 3).toBe(5); });

Diagram

Test file -> Jest runner -> assertions -> report

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q27Unit Testing

How do you test asynchronous code?

Return or await promises so the runner knows when the test finishes.

Answer

Return or await promises so the runner knows when the test finishes. Assert both success and rejection paths, and avoid tests that finish before asynchronous work completes.

Syntax

await expect(fn()).resolves.toEqual(value)

Example

Verify a service rejects with a domain error when a repository call fails.

Code example

await expect(service.load('missing')).rejects.toThrow('Not found');

Diagram

Test runner awaits promise -> resolve/reject -> assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q28Unit Testing

How do you test exceptions?

Assert that the expected error type or code is thrown or rejected.

Answer

Assert that the expected error type or code is thrown or rejected. Avoid broad assertions that pass for unrelated failures, and verify that errors are mapped correctly at API boundaries.

Syntax

expect(() => parse('bad')).toThrow(ValidationError)

Example

A parser should raise ValidationError for malformed input, not a generic TypeError.

Code example

expect(() => parseDate('not-a-date')).toThrow(ValidationError);

Diagram

Invalid input -> unit -> expected error assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q33Unit Testing

How do you test reducers or pure functions?

Pure functions are ideal unit-test targets because identical inputs should produce identical outputs without side effects.

Answer

Pure functions are ideal unit-test targets because identical inputs should produce identical outputs without side effects. Test typical values, boundaries, invalid inputs, and invariants.

Syntax

expect(reducer(state, action)).toEqual(nextState)

Example

Verify a cart reducer adds an item without mutating the original state.

Code example

const next = cartReducer(state, { type: 'add', item }); expect(state.items).toHaveLength(0); expect(next.items).toHaveLength(1);

Diagram

Input state + action -> pure function -> output state

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q35Integration Testing

What is integration testing?

Integration testing checks that components work together across a boundary, such as a service and database, API and middleware, or application and message broker.

Answer

Integration testing checks that components work together across a boundary, such as a service and database, API and middleware, or application and message broker. It catches configuration, query, serialization, and contract defects that unit tests may miss.

Syntax

test app + test database -> request -> assert

Example

Start the application with a disposable database and verify creating a user persists the expected row.

Code example

const saved = await userRepo.save({ email: 'a@example.com' }); expect(await userRepo.findById(saved.id)).toBeDefined();

Diagram

Component A + boundary + component B -> integrated behavior

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q36Integration Testing

What is the difference between unit and integration testing?

Unit tests isolate a small unit and usually replace collaborators; integration tests exercise real interactions between components.

Answer

Unit tests isolate a small unit and usually replace collaborators; integration tests exercise real interactions between components. Integration tests are generally slower and require more setup but detect boundary failures.

Syntax

unit: fake repo; integration: real test DB

Example

Test discount math alone as a unit; test that the ORM maps and saves a discount correctly as an integration test.

Code example

expect(await repository.findById(id)).toMatchObject({ discount: 10 });

Diagram

Unit: isolated logic; Integration: connected components

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q45End-to-End Testing

What are end-to-end tests?

End-to-end tests exercise a complete user journey through the running system, often via the browser or public API.

Answer

End-to-end tests exercise a complete user journey through the running system, often via the browser or public API. They provide confidence in integration but are slower and more vulnerable to environment and timing issues.

Syntax

open page -> perform action -> assert outcome

Example

Register, sign in, create a project, and verify it appears in the dashboard.

Code example

await page.goto('/login'); await page.getByLabel('Email').fill('qa@example.com');

Diagram

User -> browser -> frontend -> API -> database -> visible result

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q46End-to-End Testing

What is Playwright?

Playwright is a browser automation framework supporting Chromium, Firefox, and WebKit, with auto-waiting, locators, browser contexts, and tracing.

Answer

Playwright is a browser automation framework supporting Chromium, Firefox, and WebKit, with auto-waiting, locators, browser contexts, and tracing. Prefer accessible locators and assertions that wait for observable states.

Syntax

npx playwright test

Example

Test that a user can submit a valid login form and reach the dashboard.

Code example

await page.getByRole('button', { name: 'Sign in' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();

Diagram

Playwright runner -> browser -> application -> assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q47End-to-End Testing

What is Cypress?

Cypress is a web testing framework with a browser-based runner, retryable commands, and strong debugging support.

Answer

Cypress is a web testing framework with a browser-based runner, retryable commands, and strong debugging support. Consider its architecture, browser needs, network stubbing, and team familiarity when choosing it.

Syntax

npx cypress open; npx cypress run

Example

Visit a login page, enter credentials, submit, and assert the URL changes.

Code example

cy.visit('/login'); cy.get('[name=email]').type('qa@example.com'); cy.get('button[type=submit]').click(); cy.url().should('include', '/dashboard');

Diagram

Cypress runner -> browser -> UI actions -> retrying assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q56CI and Quality

How do you run tests in CI/CD?

A CI pipeline typically installs locked dependencies, runs lint/type checks and fast unit tests, then integration and selected E2E suites.

Answer

A CI pipeline typically installs locked dependencies, runs lint/type checks and fast unit tests, then integration and selected E2E suites. Publish reports and block release according to risk-based quality gates.

Syntax

npm ci && npm test && npm run test:e2e

Example

Run unit tests on each pull request and run longer browser tests in a controlled CI job.

Code example

steps: [{ run: 'npm ci' }, { run: 'npm test -- --runInBand' }]

Diagram

Commit -> install -> static checks -> unit -> integration/E2E -> report

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q60CI and Quality

What is a test report and what should it include?

A useful report includes pass/fail/skip counts, duration, failing assertions, logs or traces, environment details, and links to artifacts.

Answer

A useful report includes pass/fail/skip counts, duration, failing assertions, logs or traces, environment details, and links to artifacts. Reports should make failure reproduction straightforward without exposing secrets.

Syntax

JUnit XML; HTML report; screenshots/traces

Example

Publish Playwright HTML reports and JUnit output as CI artifacts after a failed run.

Code example

npx playwright test --reporter=html,junit

Diagram

Test execution -> report + artifacts -> triage

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q68Testing Fundamentals

What is a test double?

A test double is a substitute for a real collaborator, including dummy objects, stubs, spies, mocks, and fakes.

Answer

A test double is a substitute for a real collaborator, including dummy objects, stubs, spies, mocks, and fakes. Choose the simplest double that gives control over the boundary and supports a meaningful assertion.

Syntax

fake repository implements repository interface

Example

Use an in-memory repository fake for fast service tests and a real database for persistence integration tests.

Code example

class FakeRepo { private rows = new Map(); async save(x) { this.rows.set(x.id, x); } }

Diagram

System under test -> test double -> predictable boundary behavior

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q12Testing Fundamentals

What is white-box testing?

White-box testing uses knowledge of internal structure to guide tests, such as branches, conditions, and error paths.

Answer

White-box testing uses knowledge of internal structure to guide tests, such as branches, conditions, and error paths. It can improve coverage but should still assert meaningful behavior rather than implementation trivia.

Syntax

branch coverage; condition coverage

Example

Exercise both sides of an authorization check and a database failure branch.

Code example

if (isAdmin) return allow(); return deny();

Diagram

Internal branches -> tests -> coverage report

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q15Testing Fundamentals

What is exploratory testing?

Exploratory testing combines learning, test design, and execution without a fully scripted sequence.

Answer

Exploratory testing combines learning, test design, and execution without a fully scripted sequence. It is useful for discovering unexpected behavior, usability problems, and risks not covered by predefined cases.

Syntax

charter -> explore -> record findings

Example

Explore checkout with changing network conditions, browser back navigation, and unusual cart edits.

Code example

// Record session charter, observations, and reproducible defect steps

Diagram

Tester learns -> designs next probe -> observes -> adapts

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q16Testing Fundamentals

What is test coverage and what are its limits?

Coverage measures which code or behaviors were exercised, such as statements, branches, or functions.

Answer

Coverage measures which code or behaviors were exercised, such as statements, branches, or functions. High coverage does not prove correctness; assertions, test quality, and meaningful scenarios matter more than a target percentage alone.

Syntax

coverage report + meaningful assertions

Example

A test can execute a line that calculates tax but fail to assert the tax amount.

Code example

expect(calculateTax(100)).toBe(10);

Diagram

Tests -> execution coverage -> uncovered paths; assertions judge behavior

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q17Testing Fundamentals

What is test-driven development (TDD)?

TDD uses a short red-green-refactor cycle: write a failing test, implement the minimum behavior to pass, then improve design while keeping tests green.

Answer

TDD uses a short red-green-refactor cycle: write a failing test, implement the minimum behavior to pass, then improve design while keeping tests green. It is a development practice, not a substitute for all other testing.

Syntax

red -> green -> refactor

Example

Write a failing test for a discount rule before implementing the calculation.

Code example

it('applies 10% discount', () => expect(discount(100, 10)).toBe(90));

Diagram

Failing test -> implementation -> passing test -> refactor

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q18Testing Fundamentals

What is behavior-driven development (BDD)?

BDD describes behavior in shared language that product, engineering, and QA can understand.

Answer

BDD describes behavior in shared language that product, engineering, and QA can understand. Given/When/Then scenarios can connect requirements to executable acceptance tests, but should remain focused and readable.

Syntax

Given ... When ... Then ...

Example

Given an active subscription, when the user downloads a report, then access is granted.

Code example

Given('an active subscription', () => { /* setup */ });

Diagram

Business example -> executable scenario -> outcome

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q20Testing Fundamentals

What is flaky testing?

A flaky test passes and fails without a relevant code change.

Answer

A flaky test passes and fails without a relevant code change. Causes include timing assumptions, shared state, test-order dependence, unstable external services, and resource contention. Diagnose root causes instead of relying on reruns.

Syntax

same commit + same test -> inconsistent result

Example

Replace arbitrary sleep calls with a wait for a specific UI state.

Code example

await expect(page.getByText('Saved')).toBeVisible();

Diagram

Repeated runs -> inconsistent outcomes -> isolate timing/state cause

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q24Unit Testing

What is Vitest and when might you choose it?

Vitest is a test runner designed to work closely with Vite's ecosystem and supports familiar Jest-like APIs.

Answer

Vitest is a test runner designed to work closely with Vite's ecosystem and supports familiar Jest-like APIs. It can offer fast startup and shared configuration for Vite-based applications; choice depends on project tooling and compatibility.

Syntax

npx vitest run

Example

Use Vitest for a TypeScript frontend that already uses Vite and wants aligned transforms and aliases.

Code example

import { describe, it, expect } from 'vitest'; it('works', () => expect(true).toBe(true));

Diagram

Vite config + tests -> Vitest runner -> report

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q25Unit Testing

How do you mock a dependency in unit tests?

Mocks replace a collaborator with a controlled implementation so a unit can be tested independently.

Answer

Mocks replace a collaborator with a controlled implementation so a unit can be tested independently. Mock only boundaries whose behavior matters; excessive mocking can make tests mirror implementation rather than verify behavior.

Syntax

jest.fn(); vi.fn();

Example

Mock an email sender and assert registration triggers one notification without sending real email.

Code example

const send = jest.fn().mockResolvedValue(undefined); await registerUser(input, { send }); expect(send).toHaveBeenCalledTimes(1);

Diagram

Unit -> mock boundary -> controlled result -> assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q26Unit Testing

What is the difference between mocks, stubs, and spies?

A stub supplies predefined responses; a mock often includes expectations about interactions; a spy observes calls to a real or wrapped function.

Answer

A stub supplies predefined responses; a mock often includes expectations about interactions; a spy observes calls to a real or wrapped function. Terminology varies by library, so focus on the test's intent.

Syntax

stub returns value; spy observes call; mock verifies interaction

Example

Stub a repository lookup, spy on an audit logger, and verify a required notification call.

Code example

const repo = { find: jest.fn().mockResolvedValue(user) };

Diagram

System under test -> test double -> behavior verification

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q29Unit Testing

What is parameterized testing?

Parameterized tests run the same behavior against multiple input/output pairs.

Answer

Parameterized tests run the same behavior against multiple input/output pairs. They reduce duplication and are effective for boundaries, validation matrices, and combinations of business rules.

Syntax

it.each(cases)('$input -> $expected', ...)

Example

Test several invalid email forms through one clearly named test template.

Code example

it.each([['a', false], ['a@b.com', true]])('%s validity', (email, expected) => expect(isEmail(email)).toBe(expected));

Diagram

Case table -> same test logic -> multiple assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q30Unit Testing

How do you test private methods?

Usually test private behavior through the public API that depends on it.

Answer

Usually test private behavior through the public API that depends on it. Directly testing private methods couples tests to implementation and makes refactoring harder; extract a meaningful unit only if it deserves an independent contract.

Syntax

publicMethod(input) -> observable outcome

Example

Test calculateInvoice() outcomes rather than reaching into a private helper that rounds line totals.

Code example

expect(invoiceService.calculate(input).total).toBe(120);

Diagram

Public contract -> internal methods -> observable result

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q31Unit Testing

How do you test time-dependent logic?

Inject a clock or use fake timers to control time-dependent behavior.

Answer

Inject a clock or use fake timers to control time-dependent behavior. This makes expiry, scheduling, and retry tests deterministic and avoids waiting in real time.

Syntax

jest.useFakeTimers(); jest.setSystemTime(date)

Example

Test that a token expires after 15 minutes without sleeping for 15 minutes.

Code example

jest.useFakeTimers(); jest.setSystemTime(new Date('2026-01-01T00:00:00Z')); expect(isExpired(token)).toBe(false);

Diagram

Controlled clock -> time-dependent code -> deterministic assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q32Unit Testing

What is code coverage in Jest?

Jest coverage can report statements, branches, functions, and lines.

Answer

Jest coverage can report statements, branches, functions, and lines. Use it to find untested areas, then add assertions for important behaviors; a high percentage alone does not measure test effectiveness.

Syntax

jest --coverage

Example

Investigate a branch with no tests rather than adding a meaningless assertion solely to raise coverage.

Code example

// package.json: "test:coverage": "jest --coverage"

Diagram

Tests -> instrumentation -> coverage report -> risk-based follow-up

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q37Integration Testing

How do you test an Express API with Supertest?

Supertest sends HTTP requests to a Node.

Answer

Supertest sends HTTP requests to a Node.js app or server and lets tests assert status, headers, and body. Export the app separately from listening so tests can start it without binding a production port.

Syntax

request(app).get('/health').expect(200)

Example

Verify invalid registration returns 400 and a stable error schema.

Code example

import request from 'supertest'; await request(app).post('/users').send({ email: 'bad' }).expect(400);

Diagram

Test -> HTTP request -> Express middleware/routes -> response assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q38Integration Testing

How do you test a NestJS controller or provider?

NestJS Test.

Answer

NestJS Test.createTestingModule can build a testing container with real providers or overrides. Unit-test providers with mocks; use a more integrated test module when validating dependency wiring and HTTP behavior.

Syntax

Test.createTestingModule({ imports: [AppModule] })

Example

Override an email provider for a controller test while keeping validation and routing real.

Code example

const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).overrideProvider(MailerService).useValue(fakeMailer).compile();

Diagram

Test module -> Nest DI graph -> controller/service assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q39Integration Testing

How do you test database code?

Use a dedicated disposable database or isolated schema with the same engine and relevant version as production.

Answer

Use a dedicated disposable database or isolated schema with the same engine and relevant version as production. Apply migrations, create deterministic fixtures, and clean up reliably; avoid relying on a developer's local data.

Syntax

migrate -> seed -> test -> rollback/cleanup

Example

Verify a unique email constraint rejects duplicate records in the real test database.

Code example

await expect(repo.create({ email: 'same@example.com' })).rejects.toThrow();

Diagram

Test setup -> migrations/fixtures -> real DB query -> assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q40Integration Testing

What is Testcontainers?

Testcontainers provisions disposable dependencies such as databases, brokers, and caches in containers for tests.

Answer

Testcontainers provisions disposable dependencies such as databases, brokers, and caches in containers for tests. It improves environment fidelity but requires container runtime support and careful startup/cleanup.

Syntax

start container -> obtain connection URL -> run tests

Example

Start a PostgreSQL container, run migrations, then test repository behavior against it.

Code example

const container = await new PostgreSqlContainer('postgres:16').start(); const url = container.getConnectionUri();

Diagram

Test runner -> disposable service container -> integration tests -> teardown

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q41Integration Testing

How should integration test data be managed?

Use isolated fixtures, factories, transactions, unique test identifiers, or per-test schemas depending on concurrency and database behavior.

Answer

Use isolated fixtures, factories, transactions, unique test identifiers, or per-test schemas depending on concurrency and database behavior. Tests should not depend on execution order or shared mutable records.

Syntax

createFixture() -> test -> cleanup

Example

Generate a unique email per test and remove inserted rows or roll back a transaction afterward.

Code example

const email = `test-${crypto.randomUUID()}@example.com`;

Diagram

Fixture setup -> test actions -> cleanup

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q42Integration Testing

How do you test external HTTP integrations?

Separate unit tests using mocked clients from integration tests against a sandbox or controlled test server.

Answer

Separate unit tests using mocked clients from integration tests against a sandbox or controlled test server. Verify timeouts, retries, error mapping, serialization, and authentication without depending on an unstable live provider for every test run.

Syntax

nock('https://api.example.test').get('/items').reply(200, [])

Example

Simulate a 503 response and ensure the adapter maps it to a retriable domain error.

Code example

nock('https://api.example.test').get('/items').reply(503, { error: 'busy' });

Diagram

Application adapter -> controlled HTTP server/mock -> response mapping

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q48End-to-End Testing

How do you choose reliable selectors for E2E tests?

Prefer user-facing selectors such as role, accessible name, label, and stable test IDs.

Answer

Prefer user-facing selectors such as role, accessible name, label, and stable test IDs. Avoid brittle CSS classes or deep DOM paths that change during harmless UI refactors.

Syntax

getByRole('button', { name: 'Save' })

Example

Locate a Save button by its accessible name rather than a generated class name.

Code example

await page.getByRole('button', { name: 'Save' }).click();

Diagram

Accessible UI semantics -> stable locator -> action/assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q49End-to-End Testing

How do you handle waits in browser tests?

Prefer auto-waiting assertions for specific states over arbitrary sleep calls.

Answer

Prefer auto-waiting assertions for specific states over arbitrary sleep calls. Fixed delays make tests slow and still fail under variable load; wait for a response, visible state, or navigation that represents the intended behavior.

Syntax

await expect(locator).toBeVisible()

Example

Wait for a saved confirmation message instead of sleeping for two seconds.

Code example

await expect(page.getByRole('status')).toHaveText('Saved');

Diagram

Action -> application state transition -> condition-based wait

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q50End-to-End Testing

How do you test authenticated browser flows?

Test authentication itself in dedicated scenarios and reuse authenticated storage state for unrelated tests when appropriate.

Answer

Test authentication itself in dedicated scenarios and reuse authenticated storage state for unrelated tests when appropriate. Keep credentials in secrets, avoid sharing mutable accounts across parallel tests, and reset test data.

Syntax

storageState: 'playwright/.auth/user.json'

Example

Sign in once in setup, then run isolated dashboard tests with a saved test session.

Code example

await page.context().storageState({ path: 'playwright/.auth/user.json' });

Diagram

Login setup -> saved session -> isolated authenticated journeys

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q51End-to-End Testing

How do you mock network requests in Playwright?

Playwright route interception can provide deterministic responses or simulate failures.

Answer

Playwright route interception can provide deterministic responses or simulate failures. Use mocks for frontend edge cases and keep a smaller set of tests against real backend environments to catch contract mismatches.

Syntax

page.route('**/api/items', route => route.fulfill(...))

Example

Simulate an API 500 and assert that the UI displays a useful error state.

Code example

await page.route('**/api/items', route => route.fulfill({ status: 500, json: { message: 'Failed' } }));

Diagram

Browser request -> route handler/mock -> UI state assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q52End-to-End Testing

How do you test responsive layouts?

Run selected UI tests at representative viewport sizes and, where necessary, device profiles.

Answer

Run selected UI tests at representative viewport sizes and, where necessary, device profiles. Assert meaningful visibility and interaction rather than brittle exact pixel positions; combine automation with visual review.

Syntax

page.setViewportSize({ width: 390, height: 844 })

Example

Verify the mobile navigation opens and its links remain reachable on a narrow viewport.

Code example

await page.setViewportSize({ width: 390, height: 844 }); await expect(page.getByRole('button', { name: 'Menu' })).toBeVisible();

Diagram

Viewport profiles -> render/layout -> responsive behavior assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q53End-to-End Testing

What is visual regression testing?

Visual regression testing compares screenshots or rendered output against approved baselines to detect unintended UI changes.

Answer

Visual regression testing compares screenshots or rendered output against approved baselines to detect unintended UI changes. Control fonts, viewport, data, animation, and rendering environment to reduce noisy diffs.

Syntax

toHaveScreenshot('dashboard.png')

Example

Capture a stable dashboard screenshot after loading deterministic fixture data.

Code example

await expect(page).toHaveScreenshot('dashboard.png', { animations: 'disabled' });

Diagram

Render baseline + current screenshot -> diff -> review

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q54End-to-End Testing

How do you test accessibility in an automated pipeline?

Automated accessibility checks can detect some issues such as missing names, invalid ARIA, and contrast rules, but cannot replace keyboard, screen-reader, and human review.

Answer

Automated accessibility checks can detect some issues such as missing names, invalid ARIA, and contrast rules, but cannot replace keyboard, screen-reader, and human review. Test semantic roles and keyboard behavior too.

Syntax

axe scan + keyboard navigation checks

Example

Run an axe scan on a page and verify the main workflow is usable without a mouse.

Code example

const results = await new AxeBuilder({ page }).analyze(); expect(results.violations).toEqual([]);

Diagram

Rendered page -> automated a11y rules + manual assistive-tech review

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q58CI and Quality

What is test environment parity?

Environment parity means test environments resemble production in relevant ways, such as database engine, runtime, configuration, and network behavior.

Answer

Environment parity means test environments resemble production in relevant ways, such as database engine, runtime, configuration, and network behavior. Exact parity may be impractical, so identify and test differences explicitly.

Syntax

same DB engine/version; config by environment

Example

Use PostgreSQL in integration tests if production runs PostgreSQL rather than relying only on SQLite when SQL semantics matter.

Code example

// Run migrations against the same major DB engine used in production

Diagram

Production architecture -> representative test environment -> confidence

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q59CI and Quality

How do you prioritize test cases?

Prioritize by business impact, likelihood of failure, change frequency, exposure, and recovery cost.

Answer

Prioritize by business impact, likelihood of failure, change frequency, exposure, and recovery cost. Critical payment, authentication, data integrity, and tenant isolation flows often deserve stronger layered coverage.

Syntax

risk score = impact x likelihood

Example

Run high-risk authorization and payment tests on every relevant pull request.

Code example

const priority = impact * likelihood;

Diagram

Risk assessment -> test selection -> CI gates

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q61Performance Testing

How do you test APIs for performance?

Performance testing measures throughput, latency percentiles, errors, and resource usage under defined workloads.

Answer

Performance testing measures throughput, latency percentiles, errors, and resource usage under defined workloads. Separate load, stress, spike, and soak tests, and avoid treating average latency as sufficient.

Syntax

k6 run load-test.js

Example

Use a representative mix of read/write traffic and monitor p95 latency and database saturation.

Code example

import http from 'k6/http'; export default function () { http.get('https://test.example.com/health'); }

Diagram

Workload model -> load generator -> service metrics -> bottleneck analysis

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q62Performance Testing

What is the difference between load, stress, spike, and soak testing?

Load testing evaluates expected demand; stress testing pushes beyond normal capacity; spike testing checks abrupt changes; soak testing runs for an extended period to reveal leaks or degradation.

Answer

Load testing evaluates expected demand; stress testing pushes beyond normal capacity; spike testing checks abrupt changes; soak testing runs for an extended period to reveal leaks or degradation.

Syntax

baseline load -> ramp -> spike/stress -> sustained run

Example

A soak test may run for hours while watching memory, connection pools, and error rates.

Code example

// Define workload stages and thresholds in a k6 scenario

Diagram

Workload patterns -> latency/errors/resources -> capacity findings

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q64Reliability Testing

How do you test feature flags?

Test important flag states, including enabled, disabled, missing, and invalid configuration, plus rollout targeting where relevant.

Answer

Test important flag states, including enabled, disabled, missing, and invalid configuration, plus rollout targeting where relevant. Ensure both paths remain valid while a flag is active.

Syntax

flag on/off -> assert expected behavior

Example

Verify a new checkout flow and the legacy flow both work during gradual rollout.

Code example

expect(checkout({ newFlow: false })).toMatchObject({ ok: true });

Diagram

Flag state -> code path -> behavior assertions

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q69Integration Testing

How do you test a REST API schema?

Validate response bodies against an agreed schema such as OpenAPI or JSON Schema.

Answer

Validate response bodies against an agreed schema such as OpenAPI or JSON Schema. Include required fields, types, formats, and error responses so accidental contract changes are detected.

Syntax

ajv.validate(schema, response.body)

Example

Assert that a successful user response includes an ID and email with the expected types.

Code example

expect(validate(userSchema, response.body)).toBe(true);

Diagram

HTTP response -> schema validator -> contract pass/fail

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q72CI and Quality

How do you maintain a sustainable automated test suite?

Keep tests readable, deterministic, fast enough for frequent feedback, and aligned to user-visible behavior.

Answer

Keep tests readable, deterministic, fast enough for frequent feedback, and aligned to user-visible behavior. Remove obsolete duplication, quarantine flaky tests with ownership, and review test maintenance as part of feature work.

Syntax

fast feedback + stable fixtures + clear assertions

Example

Refactor duplicated setup into factories while keeping each test's scenario and assertions explicit.

Code example

beforeEach(() => { fixture = createUserFixture(); });

Diagram

Test suite -> feedback/maintenance -> reliable release confidence

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q74Integration Testing

How do you test cache behavior?

Verify cache hits, misses, expiry, invalidation after writes, and behavior when the cache is unavailable.

Answer

Verify cache hits, misses, expiry, invalidation after writes, and behavior when the cache is unavailable. Tests should ensure stale or cross-user data is not leaked through an incorrect cache key.

Syntax

get(key) -> miss/load/set -> hit; update -> invalidate

Example

Read a product twice and assert the second read uses the cache, then update it and verify the cached value is refreshed.

Code example

expect(await service.getProduct(id)).toEqual(product); expect(cache.get).toHaveBeenCalled();

Diagram

Request -> cache hit? -> data source on miss -> cache update/invalidation

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q75Reliability Testing

How do you test background jobs?

Test job payload validation, successful execution, retries, duplicate delivery, failure handling, and observability.

Answer

Test job payload validation, successful execution, retries, duplicate delivery, failure handling, and observability. Keep business logic callable independently from the queue adapter so most cases can be tested quickly.

Syntax

enqueue(job) -> worker.handle(job) -> assert outcome

Example

Run the same notification job twice and verify the idempotency mechanism prevents duplicate delivery.

Code example

await worker.handle(job); await worker.handle(job); expect(mailer.send).toHaveBeenCalledTimes(1);

Diagram

Scheduler/producer -> queue -> worker -> idempotent handler -> outcome

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios

Advanced Questions

Architecture, optimization, and design trade-offs.

Q19Testing Fundamentals

What is mutation testing?

Mutation testing introduces small faults, such as changing a comparison operator, to check whether tests detect them.

Answer

Mutation testing introduces small faults, such as changing a comparison operator, to check whether tests detect them. Surviving mutants may reveal weak assertions or missing scenarios; mutation testing can be expensive on large suites.

Syntax

mutate code -> run tests -> score killed/survived

Example

Change `>=` to `>` in a boundary check and see whether a test fails at the exact boundary.

Code example

// Use a mutation tool such as Stryker to mutate code and evaluate tests

Diagram

Source -> mutated variants -> test suite -> mutation score

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q34Unit Testing

How do you avoid over-mocking?

Mock external boundaries such as network, clock, filesystem, and persistence when needed, but keep domain logic real.

Answer

Mock external boundaries such as network, clock, filesystem, and persistence when needed, but keep domain logic real. Over-mocking can let tests pass even when components no longer work together.

Syntax

real domain logic + mocked external adapter

Example

Use a real price calculator while stubbing only the exchange-rate provider.

Code example

const result = await pricingService.total(cart, { rates: fakeRates }); expect(result.currency).toBe('USD');

Diagram

Real unit/domain behavior -> limited test doubles at boundaries

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q43Integration Testing

What is contract testing?

Contract testing checks that a provider and consumer agree on request/response shapes and semantics.

Answer

Contract testing checks that a provider and consumer agree on request/response shapes and semantics. Consumer-driven contracts can catch breaking changes without requiring a full environment for every consumer/provider combination.

Syntax

OpenAPI/Pact contract -> provider verification

Example

Verify the provider still returns the fields required by a mobile app consumer.

Code example

// Example: run provider verification against a generated Pact contract

Diagram

Consumer expectations -> contract artifact -> provider verification

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q44Integration Testing

How do you test message queues?

Test producers and consumers against a real or containerized broker when broker semantics matter.

Answer

Test producers and consumers against a real or containerized broker when broker semantics matter. Verify serialization, acknowledgement, retry, dead-letter handling, and idempotency; avoid asserting delivery order unless guaranteed.

Syntax

publish(event) -> consume -> assert effect

Example

Publish an OrderCreated event and assert the consumer updates inventory once even if the message is redelivered.

Code example

await publisher.publish(event); await waitFor(() => expect(inventory.reserve).toHaveBeenCalledTimes(1));

Diagram

Producer -> broker -> consumer -> side effect -> assertion

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q55End-to-End Testing

How do you reduce E2E test flakiness in CI?

Use deterministic test data, isolated accounts, condition-based waits, controlled dependencies, browser traces, and cleanup.

Answer

Use deterministic test data, isolated accounts, condition-based waits, controlled dependencies, browser traces, and cleanup. Retry only to diagnose or mitigate known infrastructure noise; retries should not hide product defects.

Syntax

trace: 'retain-on-failure'

Example

Capture traces and screenshots on failure to inspect whether the issue is timing, network, or application behavior.

Code example

// Playwright config: use trace: 'retain-on-failure'

Diagram

CI environment -> deterministic setup -> browser test -> artifacts on failure

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q57CI and Quality

How do you parallelize tests safely?

Parallelize independent tests while isolating databases, accounts, ports, files, and other shared resources.

Answer

Parallelize independent tests while isolating databases, accounts, ports, files, and other shared resources. Use worker-specific namespaces and avoid order-dependent fixtures; measure whether parallelism improves wall-clock time without overloading dependencies.

Syntax

workerId -> unique test namespace

Example

Give each worker a distinct database schema or tenant and clean it up afterward.

Code example

const namespace = `test-worker-${process.env.JEST_WORKER_ID ?? '1'}`;

Diagram

Workers -> isolated resources -> concurrent tests

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q63Reliability Testing

How do you test retry and timeout behavior?

Use controlled slow/failing dependencies to verify deadlines, bounded retries, backoff, jitter, and circuit breaking.

Answer

Use controlled slow/failing dependencies to verify deadlines, bounded retries, backoff, jitter, and circuit breaking. Ensure retries do not duplicate non-idempotent effects and that the overall request has a time budget.

Syntax

timeout + maxAttempts + exponential backoff

Example

Simulate a dependency that times out twice then succeeds and assert the retry cap is respected.

Code example

expect(retryOperation(operation, { attempts: 3 })).resolves.toBe('ok');

Diagram

Request -> timeout -> bounded retries/backoff -> success or safe failure

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q65Reliability Testing

How do you test idempotency?

Idempotency tests submit the same logical operation repeatedly and verify the business effect occurs once while responses remain consistent.

Answer

Idempotency tests submit the same logical operation repeatedly and verify the business effect occurs once while responses remain consistent. Also test concurrent duplicate requests and key reuse with different payloads.

Syntax

same idempotency key + same request -> same result

Example

Send the same payment request twice and assert the ledger records one charge.

Code example

const a = await charge(input, key); const b = await charge(input, key); expect(b.id).toBe(a.id);

Diagram

Repeated requests -> deduplication store -> one side effect

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q66Security Testing

How do you test authorization boundaries?

Test allowed and denied actions across roles, ownership, tenant boundaries, and object states.

Answer

Test allowed and denied actions across roles, ownership, tenant boundaries, and object states. Include direct API requests, not only UI visibility, and use fixtures that prove one tenant cannot access another tenant's data.

Syntax

user A requests user B resource -> deny

Example

Attempt to fetch another tenant's invoice by changing the ID and assert no sensitive data is returned.

Code example

await request(app).get(`/invoices/${otherTenantInvoice.id}`).set(authHeader).expect(404);

Diagram

Identity + resource + action -> policy matrix -> allow/deny

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q67Security Testing

How do you test for SQL injection?

Use safe parameterized queries and security tests with representative injection-like inputs.

Answer

Use safe parameterized queries and security tests with representative injection-like inputs. Tests should verify the payload is treated as data and cannot change query structure; do not rely on a blacklist of suspicious strings.

Syntax

parameterized query: WHERE email = $1

Example

Submit an input containing quotes and SQL syntax and verify it is rejected or treated literally.

Code example

await db.query('SELECT id FROM users WHERE email = $1', [input]);

Diagram

Untrusted input -> parameter binding -> query remains structurally fixed

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q70Integration Testing

How do you test database migrations?

Run migrations against an empty database and against a representative previous schema, then verify data preservation and constraints.

Answer

Run migrations against an empty database and against a representative previous schema, then verify data preservation and constraints. Include rollback or forward-fix strategy appropriate to the migration system.

Syntax

migrate up -> assert schema/data -> rollback if supported

Example

Test adding a non-null column to a populated table with a safe default or staged migration.

Code example

await dataSource.runMigrations(); expect(await columnExists('users', 'status')).toBe(true);

Diagram

Previous schema/data -> migration -> expected schema + preserved data

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q71CI and Quality

What is a canary release and how do tests support it?

A canary release sends a small portion of production traffic to a new version while monitoring health, errors, and latency.

Answer

A canary release sends a small portion of production traffic to a new version while monitoring health, errors, and latency. Automated smoke checks and metric-based rollback thresholds help detect regressions before wider rollout.

Syntax

deploy 5% -> observe -> expand or rollback

Example

Run post-deploy synthetic checks against the canary and automatically stop rollout if error rate crosses a threshold.

Code example

// Deploy pipeline evaluates health checks and SLO metrics before increasing traffic

Diagram

Release -> small traffic slice -> checks/metrics -> expand or rollback

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios
Q73Integration Testing

How do you test WebSocket or real-time features?

Test connection establishment, authentication, message schema, ordering guarantees, reconnect behavior, and cleanup using a controlled client and server.

Answer

Test connection establishment, authentication, message schema, ordering guarantees, reconnect behavior, and cleanup using a controlled client and server. Include disconnect and unauthorized-client cases.

Syntax

connect -> authenticate -> send event -> assert received event

Example

Connect two test clients and verify only the subscribed authorized client receives a private update.

Code example

const client = await connectWebSocket(url); await client.send(JSON.stringify({ type: 'subscribe', roomId })); await expectMessage(client, { type: 'update' });

Diagram

Client A -> WebSocket gateway -> authorized room -> Client A receives event

Key Points

  • Know when to apply this testing technique
  • Make tests deterministic and assert observable behavior
  • Include relevant failure and boundary scenarios

Share this question bank

Send this page to someone preparing for an interview.