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.
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.
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