Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add require stack & surface Yarn PnP #9681

Merged
merged 28 commits into from
Mar 25, 2020
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
b2561c2
added require stack error, missing yarn pnp error surfacing and print…
MarcoScabbiolo Mar 17, 2020
785bc10
wip
MarcoScabbiolo Mar 17, 2020
dbf1de3
all done, pending all tests run
MarcoScabbiolo Mar 18, 2020
3b34466
passing tests, updated snapshots
MarcoScabbiolo Mar 18, 2020
a1c2362
updated changelog
MarcoScabbiolo Mar 18, 2020
8d4d036
support windows separator
MarcoScabbiolo Mar 18, 2020
19b47e8
git fixes for windows
MarcoScabbiolo Mar 19, 2020
74ef00d
tests in mac
MarcoScabbiolo Mar 19, 2020
57e8a12
use inline snapshots for conditional snapshots
MarcoScabbiolo Mar 19, 2020
0483d94
update spanshot
MarcoScabbiolo Mar 19, 2020
644a5aa
windows snapshots
MarcoScabbiolo Mar 19, 2020
f51e1c4
unix paths in require stack error
MarcoScabbiolo Mar 23, 2020
1b92748
build require stack from module parent in the modules runtime, unix p…
MarcoScabbiolo Mar 23, 2020
9497303
fix in runtime errors
Mar 23, 2020
006e565
fix return type for handleRuntimeError
Mar 23, 2020
918fea0
Merge branch 'master' of https://github.com/facebook/jest
Mar 23, 2020
8b690e1
extend ModuleNotFoundError to accomodate requireStack and hint coexis…
Mar 23, 2020
aeea791
fix test reporter test, better ModuleNotFoundError constructor
Mar 23, 2020
a5660af
Update CHANGELOG.md
MarcoScabbiolo Mar 24, 2020
17b3346
fix moduelnotfounderror casting and extension hint reporting
Mar 24, 2020
b8d024d
Merge branch 'master' of github.com:MarcoScabbiolo/jest
Mar 24, 2020
27628f4
update snapshots
Mar 24, 2020
685d2da
try to find a sibling with a similar extension only once, when when t…
Mar 24, 2020
fcfc5de
updated snapshots
Mar 24, 2020
5a4eafd
updated snapshots
Mar 24, 2020
5a805e5
updated snapshots
Mar 25, 2020
b3cb409
use .toThrow rather than try-catch in tests
SimenB Mar 25, 2020
d334051
whitespace
SimenB Mar 25, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Features

- `[jest-runtime]` Require stack in the errors message when a module cannot be resolved ([#9681](https://github.com/facebook/jest/pull/9681))
- `[jest-config]` Support ESM config files with `.js` extension ([#9573](https://github.com/facebook/jest/pull/9573)).
- `[jest-runtime]` Override `module.createRequire` to return a Jest-compatible `require` function ([#9469](https://github.com/facebook/jest/pull/9469))
- `[jest-haste-map]` [**BREAKING**] Remove `mapper` option ([#9581](https://github.com/facebook/jest/pull/9581))
Expand All @@ -10,6 +11,7 @@

### Fixes

- `[jest-runtime]` Yarn PnP errors surfaced to the user ([#9681](https://github.com/facebook/jest/pull/9681))
- `[expect]` Handle readonly properties correctly ([#9575](https://github.com/facebook/jest/pull/9575))
- `[jest-cli]` Set `coverageProvider` correctly when provided in config ([#9562](https://github.com/facebook/jest/pull/9562))
- `[jest-cli]` Allow specifying `.cjs` and `.mjs` config files by `--config` CLI option ([#9578](https://github.com/facebook/jest/pull/9578))
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/__snapshots__/moduleNameMapper.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ FAIL __tests__/index.js
12 | module.exports = () => 'test';
13 |

at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:519:17)
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:525:17)
at Object.require (index.js:10:1)
`;

Expand Down Expand Up @@ -65,6 +65,6 @@ FAIL __tests__/index.js
12 | module.exports = () => 'test';
13 |

at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:519:17)
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:525:17)
at Object.require (index.js:10:1)
`;
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ FAIL __tests__/test.js

Cannot find module './some-json-file' from 'index.js'

Require stack:
index.js
__tests__/test.js


However, Jest was able to find:
'./some-json-file.json'

Expand All @@ -32,6 +37,6 @@ FAIL __tests__/test.js
| ^
9 |

at Resolver.resolveModule (../../packages/jest-resolve/build/index.js:276:11)
at Resolver.resolveModule (../../packages/jest-resolve/build/index.js:282:11)
at Object.require (index.js:8:18)
`;
2 changes: 1 addition & 1 deletion e2e/__tests__/pnp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ it('sucessfully runs the tests inside `pnp/`', () => {
nodeOptions: `--require ${DIR}/.pnp.js`,
});
expect(json.success).toBe(true);
expect(json.numTotalTestSuites).toBe(1);
expect(json.numTotalTestSuites).toBe(2);
});
1 change: 1 addition & 0 deletions e2e/__tests__/resolveNoFileExtensions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ test('show error message with matching files', () => {
const {rest} = extractSummary(stderr);

expect(exitCode).toBe(1);

MarcoScabbiolo marked this conversation as resolved.
Show resolved Hide resolved
expect(wrap(rest)).toMatchSnapshot();
});

Expand Down
16 changes: 16 additions & 0 deletions e2e/pnp/__tests__/undeclared-dependency.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/

it('should surface pnp errors', () => {
try {
require('undeclared');
throw new Error('UNDECLARED_DEPENDENCY should have been thrown');
} catch (error) {
expect(error.code).toBe('UNDECLARED_DEPENDENCY');
}
});
3 changes: 2 additions & 1 deletion e2e/pnp/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"dependencies": {
"foo": "link:./lib"
"foo": "link:./lib",
"undeclared": "link:./undeclared-dependency"
},
"installConfig": {
"pnp": true
Expand Down
11 changes: 11 additions & 0 deletions e2e/pnp/undeclared-dependency/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/

const nope = require('unesitent_module__');

module.exports = () => nope;
3 changes: 3 additions & 0 deletions e2e/pnp/undeclared-dependency/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"version": "0.0.0"
}
4 changes: 4 additions & 0 deletions e2e/pnp/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@
"foo@link:./lib":
version "0.0.0"
uid ""

"undeclared@link:./undeclared-dependency":
version "0.0.0"
uid ""
12 changes: 12 additions & 0 deletions e2e/resolve/Test7.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/

require('./test1');
const requiresUnexistingModule = require('./requiresUnexistingModule');

module.exports = {module: requiresUnexistingModule};
41 changes: 35 additions & 6 deletions e2e/resolve/__tests__/resolve.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,40 @@ test('should require resolve haste mocks correctly', () => {
expect(require('Test6').key).toBe('mock');
});

test('should throw module not found error if the module has dependencies that cannot be found', () => {
try {
require('Test7');
throw new Error('Requiring Test7 should have thrown an error');
} catch (error) {
expect(error.code).toBe('MODULE_NOT_FOUND');

expect(error.message).toMatchInlineSnapshot(`
"Cannot find module 'nope' from 'requiresUnexistingModule.js'

Require stack:
requiresUnexistingModule.js
Test7.js
__tests__/resolve.test.js


However, Jest was able to find:
'./requiresUnexistingModule.js'

You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].

See https://jestjs.io/docs/en/configuration#modulefileextensions-arraystring"
`);
}
});

test('should throw module not found error if the module cannot be found', () => {
expect(() => require('Test7')).toThrow(
expect.objectContaining({
code: 'MODULE_NOT_FOUND',
message: "Cannot find module 'Test7' from 'resolve.test.js'",
})
);
try {
require('Test8');
throw new Error('Requiring Test8 should have thrown an error');
} catch (error) {
expect(error.code).toBe('MODULE_NOT_FOUND');
expect(error.message.split('\n')[0]).toBe(
"Cannot find module 'Test8' from 'resolve.test.js'"
);
}
});
12 changes: 12 additions & 0 deletions e2e/resolve/requiresUnexistingModule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/

require('./test2');
const unexistedModule = require('nope');

module.exports = {module: unexistedModule};
13 changes: 10 additions & 3 deletions packages/jest-resolve/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type FindNodeModuleConfig = {
paths?: Array<Config.Path>;
resolver?: Config.Path | null;
rootDir?: Config.Path;
throwIfNotFound?: boolean;
};

type BooleanObject = Record<string, boolean>;
Expand Down Expand Up @@ -105,7 +106,11 @@ class Resolver {
paths: paths ? (nodePaths || []).concat(paths) : nodePaths,
rootDir: options.rootDir,
});
} catch (e) {}
} catch (e) {
if (options.throwIfNotFound) {
throw e;
}
}
return null;
}

Expand Down Expand Up @@ -155,7 +160,7 @@ class Resolver {
const skipResolution =
options && options.skipNodeResolution && !moduleName.includes(path.sep);

const resolveNodeModule = (name: Config.Path) =>
const resolveNodeModule = (name: Config.Path, throwIfNotFound = false) =>
Resolver.findNodeModule(name, {
basedir: dirname,
browser: this._options.browser,
Expand All @@ -164,10 +169,12 @@ class Resolver {
paths,
resolver: this._options.resolver,
rootDir: this._options.rootDir,
throwIfNotFound,
});

if (!skipResolution) {
module = resolveNodeModule(moduleName);
// @ts-ignore: the "pnp" version named isn't in DefinitelyTyped
module = resolveNodeModule(moduleName, Boolean(process.versions.pnp));

if (module) {
this._moduleNameCache.set(key, module);
Expand Down
42 changes: 42 additions & 0 deletions packages/jest-runtime/src/RuntimeModuleNotFoundError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import * as path from 'path';
import {ModuleNotFoundError} from 'jest-resolve';
import {Config} from '@jest/types';
MarcoScabbiolo marked this conversation as resolved.
Show resolved Hide resolved
import slash = require('slash');

export default class RuntimeModuleNotFoundError extends ModuleNotFoundError {
public hint?: string;
public requireStack?: Array<Config.Path>;
public stackTraceBuilt?: boolean;

public static buildMessage(
MarcoScabbiolo marked this conversation as resolved.
Show resolved Hide resolved
error: RuntimeModuleNotFoundError,
rootDir: Config.Path,
): void {
if (
!error.stackTraceBuilt &&
error?.requireStack?.length &&
error?.requireStack?.length > 1
) {
error.message += `

Require stack:
${(error.requireStack as Array<string>)
.map(p => p.replace(`${rootDir}${path.sep}`, ''))
.map(slash)
.join('\n ')}
`;
error.stackTraceBuilt = true;
}

if (error.hint) {
error.message += error.hint;
}
}
}
75 changes: 49 additions & 26 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import HasteMap = require('jest-haste-map');
import Resolver = require('jest-resolve');
import Snapshot = require('jest-snapshot');
import stripBOM = require('strip-bom');
import RuntimeModuleNotFoundError from './RuntimeModuleNotFoundError';

type HasteMapOptions = {
console?: Console;
Expand Down Expand Up @@ -511,15 +512,11 @@ class Runtime {
}
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
const appendedMessage = findSiblingsWithFileExtension(
e.hint = findSiblingsWithFileExtension(
this._config.moduleFileExtensions,
from,
moduleName,
);

if (appendedMessage) {
e.message += appendedMessage;
}
}
throw e;
}
Expand Down Expand Up @@ -841,28 +838,32 @@ class Runtime {
return;
}

compiledFunction.call(
localModule.exports,
localModule as NodeModule, // module object
localModule.exports, // module exports
localModule.require as typeof require, // require implementation
dirname, // __dirname
filename, // __filename
this._environment.global, // global object
this._createJestObjectFor(
filename,
localModule.require as LocalModuleRequire,
), // jest object
...this._config.extraGlobals.map(globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}
try {
compiledFunction.call(
localModule.exports,
localModule as NodeModule, // module object
localModule.exports, // module exports
localModule.require as typeof require, // require implementation
dirname, // __dirname
filename, // __filename
this._environment.global, // global object
this._createJestObjectFor(
filename,
localModule.require as LocalModuleRequire,
), // jest object
...this._config.extraGlobals.map(globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
}

throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
}),
);
throw new Error(
`You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.`,
);
}),
);
} catch (error) {
this.handleExecutionError(error, localModule);
}

this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock;
this._currentlyExecutingModulePath = lastExecutingModulePath;
Expand Down Expand Up @@ -1286,6 +1287,28 @@ class Runtime {
...this._config.extraGlobals,
];
}

private handleExecutionError(e: Error, module: InitialModule): void {
MarcoScabbiolo marked this conversation as resolved.
Show resolved Hide resolved
const runtimeModuleNotFoundError = e as RuntimeModuleNotFoundError;
if (runtimeModuleNotFoundError.code === 'MODULE_NOT_FOUND') {
runtimeModuleNotFoundError.requireStack = [module.filename || module.id];

for (let cursor = module.parent; cursor; cursor = cursor.parent) {
runtimeModuleNotFoundError.requireStack.push(
cursor.filename || cursor.id,
);
}

RuntimeModuleNotFoundError.buildMessage(
runtimeModuleNotFoundError,
this._config.rootDir,
);

throw runtimeModuleNotFoundError;
}

throw e;
}
}

export = Runtime;