From 3f4fb07a6f16778bfaadb872454be4db23d6af8b Mon Sep 17 00:00:00 2001 From: Gustaf Dalemar Date: Mon, 22 Jan 2018 18:46:13 +0100 Subject: [PATCH] fix(roc-plugin-repo): Fix Jest resolver when using moduleNameMapper --- .../src/commands/utils/jest/roc-resolver.js | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/extensions/roc-plugin-repo/src/commands/utils/jest/roc-resolver.js b/extensions/roc-plugin-repo/src/commands/utils/jest/roc-resolver.js index fa1e485..b841f0f 100644 --- a/extensions/roc-plugin-repo/src/commands/utils/jest/roc-resolver.js +++ b/extensions/roc-plugin-repo/src/commands/utils/jest/roc-resolver.js @@ -1,6 +1,7 @@ -// This version of Roc might not be the same version as is used in the project to launch the CLI +import fs from 'fs'; import resolveFrom from 'resolve-from'; +// This version of Roc might not be the same version as is used in the project to launch the CLI require('roc').runCli({ invoke: false, argv: JSON.parse(process.env.ROC_INITAL_ARGV), @@ -14,6 +15,24 @@ const jestDefaultResolver = require(resolveFrom( )).default; const callsites = require('callsites'); +// This finds the line number for an error that Jest throws when there is a problem +// with moduleNameMapper resolving. We use this to find a reference for when we should +// short-circuit the resolver since it is called in two places for _resolveStubModuleName +const lineNumberForModuleMapperError = + fs + .readFileSync( + resolveFrom(require.resolve('jest'), 'jest-resolve/build/index.js'), + 'utf8', + ) + .split('\n') + .findIndex(row => /Could not locate module/.test(row)) + 1; + +if (lineNumberForModuleMapperError === 0) { + throw new Error( + 'The integration between Jest and roc-plugin-repo is out of date, please update roc-plugin-repo.', + ); +} + module.exports = function customJestResolver(path, options) { // This logic manages a bug in Jest that makes mocking fail and should be removed // as soon as this problem is addressed. What we are doing here is that we disable @@ -27,7 +46,11 @@ module.exports = function customJestResolver(path, options) { // don't want but adding detection on line number is too fragile. // // https://github.com/facebook/jest/issues/4985 - if (callsites()[2].getMethodName() === '_resolveStubModuleName') { + const cs = callsites()[2]; + if ( + cs.getMethodName() === '_resolveStubModuleName' && + cs.getLineNumber() > lineNumberForModuleMapperError + ) { return null; } // return jestDefaultResolver(path, options);