jestjs/jest

Allow mocking `require.resolve`

Open

#9.543 aberto em 9 de fev. de 2020

Ver no GitHub
 (26 comments) (20 reactions) (0 assignees)TypeScript (6.653 forks)batch import
:rocket: Feature RequestHelp WantedPinned

Métricas do repositório

Stars
 (45.361 stars)
Métricas de merge de PR
 (Mesclagem média 11d 22h) (11 fundiu PRs em 30d)

Description

🚀 Feature Proposal

The require.resolve function is re-created for every file: this is needed so that it starts resolving from the correct location.

However, this makes it impossible to mock it: require.resolve = jest.fn() doesn't work. I propose adding an API similar to jest.mock specifically for require.resolve's behavior.

Motivation

We have different tests in @babel/core that test plugins/presets aliasing (ref). For example, we test that when someone uses @babel/env in their config Babel tries to resolve @babel/preset-env.

We currently rely on "fake" node_modules folders, however:

  1. We don't want to test node's resolution algorithm, we should only test what we are asking node to resolve.
  2. Using real FS just to check plugins/presets aliasing makes our tests slower.
  3. This approach doesn't work with Yarn PnP, because it changes the resolution behavior (and it shouldn't affect our tests).

Example

Maybe something like this?

jest.mockResolution("@babel/env", __dirname + "/fake/@babel/preset-env");

// test

jest.unmockResolution("@babel/env");

Pitch

Mocks are already handled by the Jest core platform :grin:

Guia do colaborador