liveBook · Manning

Jest.mock

As explained in The Art of Unit Testing 3e

A Jest API that replaces a specified imported or required module with an automatically generated or configured mock.

jest.mock replaces a required module with a fake module, saving you from manually wiring dependencies in tests. Use it when code has hard-coded dependencies such as configuration services or loggers. Jest uses “mock” for both stubbing returned values and verifying calls, so the terminology can blur two different jobs. section 5.2 section 5.2.1

Stub configuration and verify logging

jest.mock("./complicated-logger"); jest.mock("./configuration-service"); const { verifyPassword } = require("./password-verifier"); const logger = require("./complicated-logger"); const configuration = require("./configuration-service"); test("logs a passing result", () => { configuration.getLogLevel.mockReturnValue("info"); verifyPassword("anything", []); expect(logger.info).toHaveBeenCalledWith(expect.stringMatching(/PASS/)); }); Place the jest.mock calls at the top of the spec file. Reset mocks between tests so call history and configuration do not leak. section 5.2 section 5.2.1

Use the API deliberately:

  • Stub incoming behavior such as getLogLevel with mockReturnValue. section 5.2
  • Verify outgoing behavior such as a logger’s info call with Jest expectations. section 5.2
  • Prefer an abstraction or adapter around dependencies you control; direct module mocks bind tests to external APIs and make breaking changes expensive. section 5.2.2
  • Treat module mocking as especially useful for legacy code or dependencies you cannot easily change, not as a substitute for better boundaries. section 5.2.2
Listing 5.2 Faking the module APIs directly with jest.mock()
jest.mock("./complicated-logger");                              #1
jest.mock("./configuration-service");                           #1
 
const { stringMatching } = expect;
const { verifyPassword } = require("./password-verifier");
const mockLoggerModule = require("./complicated-logger");       #2
const stubConfigModule = require("./configuration-service");    #2
 
describe("password verifier", () => {
  afterEach(jest.resetAllMocks);                                #3
 
  test('with info log level and no rules, 
          it calls the logger with PASSED', () => {
    stubConfigModule.getLogLevel.mockReturnValue("info");       #4
 
    verifyPassword("anything", []);
 
    expect(mockLoggerModule.info)                               #5
      .toHaveBeenCalledWith(stringMatching(/PASS/));            #5
  });
 
  test('with debug log level and no rules, 
        it calls the logger with PASSED', () => {
    stubConfigModule.getLogLevel.mockReturnValue("debug");      #6
 
    verifyPassword("anything", []);
 
    expect(mockLoggerModule.debug)                              #7
      .toHaveBeenCalledWith(stringMatching(/PASS/));            #7
  });
});
#1 Faking the modules
#2 Getting the fake instances of the modules
#3 Telling Jest to reset any fake module behavior between tests
#4 Configuring the stub to return a fake “info” value.
#5 Asserting that the mock was called correctly
#6 Changing the stub config
#7 Asserting on the mock logger as done previously

Inspect the complete example showing module replacement, test-time configuration, call verification, and mock reset. section 5.2

How The Art of Unit Testing 3e covers it

How deep it goes
Explains module replacement, configuration, verification, reset, and hoisting while deferring Jest’s broader API surface.
Examples
Uses a Password Verifier with configuration-service and complicated-logger modules, including log-level stubbing and call assertions.
What it assumes
Assumes JavaScript module dependencies and basic tests while distinguishing stubbing from call-verification terminology.
What you can do after
Apply it via Jest to fake required modules, configure returned values, verify calls, and reset test doubles.
How it connects
Connects stubs and mocks with dependency abstraction, onion architecture, hexagonal architecture, and ports and adapters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Unit Testing 3e. The section links point to the parts of the book it draws on.