question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItĀ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Allow mocking `require.resolve`

See original GitHub issue

šŸš€ 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 😁

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:15
  • Comments:25 (13 by maintainers)

github_iconTop GitHub Comments

12reactions
SimenBcommented, Oct 18, 2020

The feature has been accepted, so no need to try to convince us šŸ™‚ PR very much welcome!

2reactions
TheHumbleJestercommented, Apr 20, 2020

Hey guys ! I know that’s not exactly what you’re looking for, but here’s my workaround to be able to ā€œmockā€ require.resolve. There’s an interesting feature in jest allowing you to define your own module resolver: https://jestjs.io/docs/en/configuration#resolver-string

Having that in mind, here is, basically, what I’ve done:

  • I created my own resolver like so:
const glob = require('glob');

let mapping = {};

// Looks for "module-resolution.json" files in all the `__tests__` directories
glob
  .sync(`${__dirname}/../../packages/**/src/**/__tests__/modules-resolution.json`)
  .forEach((file) => {
    // For each of them, merges them in the "mapping" object
    mapping = { ...mapping, ...require(file) };
  });

function resolver(path, options) {
  // If the path corresponds to a key in the mapping object, returns the fakely resolved path
  // otherwise it calls the Jest's default resolver
  return mapping[path] || options.defaultResolver(path, options);
}

module.exports = resolver;
  • Then, I configured it in my jest config file:
module.exports = {
  roots: ['<rootDir>'],
  testMatch: ['<rootDir>/packages/**/__tests__/**/*.test.js'],
  collectCoverageFrom: ['packages/**/src/**/*.js', '!packages/**/src/__tests__/**'],
  resolver: '<rootDir>/test-utils/resolver',
};
  • Finally, I can create modules-resolution.json files in my test folders that look like this:
{
  "fake-module": "/path/to/fake-module"
}

This do the job for me so far and I think that, starting from this example, we could do something more complex but more developer friendly ! Of course, that would be even better if this feature could be directly included in jest ! Anyway, I hope this will help some of you šŸ˜‰

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mocking and testing require.resolve calls in jest - Stack Overflow
I created my own resolver like so: const glob = require('glob'); let mapping = {}; // Looks for "moduleĀ ...
Read more >
How to mock a dependency in a Node.js, and why you should ...
As a good start — let's test simple module. The SkyNet. import React, { PropTypes } from 'react'; import destroyAllHumans from 'very-actions';
Read more >
[Solved]-Mocking and testing require.resolve calls in jest-node.js
I created my own resolver like so: const glob = require('glob'); let mapping = {}; // Looks for "module-resolution.json" files in all the...
Read more >
Manual Mocks - Jest
In order to mock properly, Jest needs jest.mock('moduleName') to be in the same scope as the require/import statement. Here's a contrivedĀ ...
Read more >
mock-require JavaScript and Node.js code examples - Tabnine
const mock = function (path, obj) { return mockRequire(resolve(path), obj);
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found