JavaScript & TypeScript / Quiz

jest.mock and the Hoisting Underworld

Why jest.mock works above its own imports, the out-of-scope variable error, requireActual partial mocks, and __mocks__ folder rules.

Difficulty
Hard
Format
Quiz
Points
200
Estimate
11 min

// MISSION BRIEF

Your Mission

jest.mock looks like a function call but behaves like a spell: it teleports to the top of the file, runs before your imports, and enforces scoping rules that surprise everyone exactly once.

This quiz covers the machinery: hoisting via Babel, the mock-prefix escape hatch, partial mocks with requireActual, manual mock folders, and module registry isolation.

Speed bonus active.

// FIRST CONTACT

Battle teaser

jest.mock('./mailer') is written BELOW the import of './mailer', yet the import still receives the mock. How?

  1. ANode.js resolves jest.mock calls at parse time natively
  2. BIt does not work below imports; the mock is silently ignored
  3. Cbabel-plugin-jest-hoist rewrites the file so jest.mock calls execute before import statements resolve, letting the module registry serve the mock to the import
  4. DImports in test files are lazy by default, deferring until first use
Answers, scoring, hints, and the full battle stay sealed.

// SKILL TAGS

javascriptjestmockingmodulesunit-testing