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

fix: pass resolve conditions when loading stub module #15489

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
- `[jest-util]` Always load `mjs` files with `import` ([#15447](https://github.com/jestjs/jest/pull/15447))
- `[jest-worker]` Properly handle a circular reference error when worker tries to send an assertion fails where either the expected or actual value is circular ([#15191](https://github.com/jestjs/jest/pull/15191))
- `[jest-worker]` Properly handle a BigInt when worker tries to send an assertion fails where either the expected or actual value is BigInt ([#15191](https://github.com/jestjs/jest/pull/15191))
- `[jest-resolve,jest-runtime,jest-resolve-dependencies]` Pass the conditions when resolving stub modules ([#15489](https://github.com/jestjs/jest/pull/15489))

### Performance

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 @@ -41,7 +41,7 @@ exports[`moduleNameMapper wrong array configuration 1`] = `
12 | module.exports = () => 'test';
13 |

at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1182:17)
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1184:17)
at Object.require (index.js:10:1)
at Object.require (__tests__/index.js:10:20)"
`;
Expand Down Expand Up @@ -71,7 +71,7 @@ exports[`moduleNameMapper wrong configuration 1`] = `
12 | module.exports = () => 'test';
13 |

at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1182:17)
at createNoMappedModuleFoundError (../../packages/jest-resolve/build/index.js:1184:17)
at Object.require (index.js:10:1)
at Object.require (__tests__/index.js:10:20)"
`;
14 changes: 14 additions & 0 deletions e2e/resolve-conditions/__tests__/module-name-mapper.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @jest-environment jest-environment-jsdom
*/

import {fn} from 'fake-dual-dep2';

test('returns correct message', () => {
expect(fn()).toBe('from browser');
});
10 changes: 10 additions & 0 deletions e2e/resolve-conditions/node_modules/fake-dual-dep2/browser.mjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions e2e/resolve-conditions/node_modules/fake-dual-dep2/node.mjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions e2e/resolve-conditions/node_modules/fake-dual-dep2/package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions e2e/resolve-conditions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
"testMatch": [
"<rootDir>/**/*.test.*"
],
"moduleNameMapper": {
"^fake-dual-dep2$": "fake-dual-dep2"
},
"transform": {}
}
}
10 changes: 8 additions & 2 deletions packages/jest-resolve-dependencies/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export class DependencyResolver {

resolve(file: string, options?: ResolveModuleConfig): Array<string> {
const dependencies = this._hasteFS.getDependencies(file);
const fallbackOptions: ResolveModuleConfig = {conditions: undefined};
if (!dependencies) {
return [];
}
Expand All @@ -51,11 +52,15 @@ export class DependencyResolver {
resolvedDependency = this._resolver.resolveModule(
file,
dependency,
options,
options ?? fallbackOptions,
);
} catch {
try {
resolvedDependency = this._resolver.getMockModule(file, dependency);
resolvedDependency = this._resolver.getMockModule(
file,
dependency,
options ?? fallbackOptions,
);
} catch {
// leave resolvedDependency as undefined if nothing can be found
}
Expand All @@ -73,6 +78,7 @@ export class DependencyResolver {
resolvedMockDependency = this._resolver.getMockModule(
resolvedDependency,
path.basename(dependency),
options ?? fallbackOptions,
);
} catch {
// leave resolvedMockDependency as undefined if nothing can be found
Expand Down
8 changes: 7 additions & 1 deletion packages/jest-resolve/src/__tests__/resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -742,7 +742,9 @@ describe('getMockModuleAsync', () => {
} as ResolverConfig);
const src = require.resolve('../');

await resolver.resolveModuleAsync(src, 'dependentModule');
await resolver.resolveModuleAsync(src, 'dependentModule', {
conditions: ['browser'],
});

expect(mockUserResolverAsync.async).toHaveBeenCalled();
expect(mockUserResolverAsync.async.mock.calls[0][0]).toBe(
Expand All @@ -752,6 +754,10 @@ describe('getMockModuleAsync', () => {
'basedir',
path.dirname(src),
);
expect(mockUserResolverAsync.async.mock.calls[0][1]).toHaveProperty(
'conditions',
['browser'],
);
});
});

Expand Down
76 changes: 53 additions & 23 deletions packages/jest-resolve/src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,11 +341,11 @@
resolveModule(
from: string,
moduleName: string,
options?: ResolveModuleConfig,
options: ResolveModuleConfig,
): string {
const dirname = path.dirname(from);
const module =
this.resolveStubModuleName(from, moduleName) ||
this.resolveStubModuleName(from, moduleName, options) ||
this.resolveModuleFromDirIfExists(dirname, moduleName, options);
if (module) return module;

Expand All @@ -362,7 +362,7 @@
): Promise<string> {
const dirname = path.dirname(from);
const module =
(await this.resolveStubModuleNameAsync(from, moduleName)) ||
(await this.resolveStubModuleNameAsync(from, moduleName, options)) ||
(await this.resolveModuleFromDirIfExistsAsync(
dirname,
moduleName,
Expand Down Expand Up @@ -482,25 +482,37 @@
);
}

getMockModule(from: string, name: string): string | null {
getMockModule(
from: string,
name: string,
options: Pick<ResolveModuleConfig, 'conditions'>,
): string | null {
const mock = this._moduleMap.getMockModule(name);
if (mock) {
return mock;
} else {
const moduleName = this.resolveStubModuleName(from, name);
const moduleName = this.resolveStubModuleName(from, name, options);
if (moduleName) {
return this.getModule(moduleName) || moduleName;
}
}
return null;
}

async getMockModuleAsync(from: string, name: string): Promise<string | null> {
async getMockModuleAsync(
from: string,
name: string,
options: Pick<ResolveModuleConfig, 'conditions'>,
): Promise<string | null> {

Check warning on line 506 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L506

Added line #L506 was not covered by tests
const mock = this._moduleMap.getMockModule(name);
if (mock) {
return mock;
} else {
const moduleName = await this.resolveStubModuleNameAsync(from, name);
const moduleName = await this.resolveStubModuleNameAsync(

Check warning on line 511 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L511

Added line #L511 was not covered by tests
from,
name,
options,
);
if (moduleName) {
return this.getModule(moduleName) || moduleName;
}
Expand Down Expand Up @@ -536,7 +548,7 @@
virtualMocks: Map<string, boolean>,
from: string,
moduleName = '',
options?: ResolveModuleConfig,
options: ResolveModuleConfig,
): string {
const stringifiedOptions = options ? JSON.stringify(options) : '';
const key = from + path.delimiter + moduleName + stringifiedOptions;
Expand All @@ -552,7 +564,7 @@
moduleName,
options,
);
const mockPath = this._getMockPath(from, moduleName);
const mockPath = this._getMockPath(from, moduleName, options);

Check warning on line 567 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L567

Added line #L567 was not covered by tests

const sep = path.delimiter;
const id =
Expand All @@ -570,7 +582,7 @@
virtualMocks: Map<string, boolean>,
from: string,
moduleName = '',
options?: ResolveModuleConfig,
options: ResolveModuleConfig,
): Promise<string> {
const stringifiedOptions = options ? JSON.stringify(options) : '';
const key = from + path.delimiter + moduleName + stringifiedOptions;
Expand All @@ -589,7 +601,7 @@
moduleName,
options,
);
const mockPath = await this._getMockPathAsync(from, moduleName);
const mockPath = await this._getMockPathAsync(from, moduleName, options);

Check warning on line 604 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L604

Added line #L604 was not covered by tests

const sep = path.delimiter;
const id =
Expand All @@ -611,15 +623,15 @@
virtualMocks: Map<string, boolean>,
from: string,
moduleName: string,
options?: ResolveModuleConfig,
options: ResolveModuleConfig,
): string | null {
if (this.isCoreModule(moduleName)) {
return moduleName;
}
if (moduleName.startsWith('data:')) {
return moduleName;
}
return this._isModuleResolved(from, moduleName)
return this._isModuleResolved(from, moduleName, options)
? this.getModule(moduleName)
: this._getVirtualMockPath(virtualMocks, from, moduleName, options);
}
Expand All @@ -628,7 +640,7 @@
virtualMocks: Map<string, boolean>,
from: string,
moduleName: string,
options?: ResolveModuleConfig,
options: ResolveModuleConfig,
): Promise<string | null> {
if (this.isCoreModule(moduleName)) {
return moduleName;
Expand All @@ -639,32 +651,38 @@
const isModuleResolved = await this._isModuleResolvedAsync(
from,
moduleName,
options,
);
return isModuleResolved
? this.getModule(moduleName)
: this._getVirtualMockPathAsync(virtualMocks, from, moduleName, options);
}

private _getMockPath(from: string, moduleName: string): string | null {
private _getMockPath(
from: string,
moduleName: string,
options: Pick<ResolveModuleConfig, 'conditions'>,
): string | null {

Check warning on line 665 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L665

Added line #L665 was not covered by tests
return this.isCoreModule(moduleName)
? null
: this.getMockModule(from, moduleName);
: this.getMockModule(from, moduleName, options);

Check warning on line 668 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L668

Added line #L668 was not covered by tests
}

private async _getMockPathAsync(
from: string,
moduleName: string,
options: Pick<ResolveModuleConfig, 'conditions'>,
): Promise<string | null> {
return this.isCoreModule(moduleName)
? null
: this.getMockModuleAsync(from, moduleName);
: this.getMockModuleAsync(from, moduleName, options);

Check warning on line 678 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L678

Added line #L678 was not covered by tests
}

private _getVirtualMockPath(
virtualMocks: Map<string, boolean>,
from: string,
moduleName: string,
options?: ResolveModuleConfig,
options: ResolveModuleConfig,
): string {
const virtualMockPath = this.getModulePath(from, moduleName);
return virtualMocks.get(virtualMockPath)
Expand All @@ -688,23 +706,33 @@
: from;
}

private _isModuleResolved(from: string, moduleName: string): boolean {
private _isModuleResolved(
from: string,
moduleName: string,
options: Pick<ResolveModuleConfig, 'conditions'>,
): boolean {

Check warning on line 713 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L713

Added line #L713 was not covered by tests
return !!(
this.getModule(moduleName) || this.getMockModule(from, moduleName)
this.getModule(moduleName) ||
this.getMockModule(from, moduleName, options)

Check warning on line 716 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L716

Added line #L716 was not covered by tests
);
}

private async _isModuleResolvedAsync(
from: string,
moduleName: string,
options: Pick<ResolveModuleConfig, 'conditions'>,
): Promise<boolean> {
return !!(
this.getModule(moduleName) ||
(await this.getMockModuleAsync(from, moduleName))
(await this.getMockModuleAsync(from, moduleName, options))

Check warning on line 727 in packages/jest-resolve/src/resolver.ts

View check run for this annotation

Codecov / codecov/patch

packages/jest-resolve/src/resolver.ts#L727

Added line #L727 was not covered by tests
);
}

resolveStubModuleName(from: string, moduleName: string): string | null {
resolveStubModuleName(
from: string,
moduleName: string,
options: Pick<ResolveModuleConfig, 'conditions'>,
): string | null {
const dirname = path.dirname(from);

const {extensions, moduleDirectory, paths} = this._prepareForResolution(
Expand All @@ -727,11 +755,11 @@
let module: string | null = null;
for (const possibleModuleName of possibleModuleNames) {
const updatedName = mapModuleName(possibleModuleName);

module =
this.getModule(updatedName) ||
Resolver.findNodeModule(updatedName, {
basedir: dirname,
conditions: options?.conditions,
extensions,
moduleDirectory,
paths,
Expand Down Expand Up @@ -763,6 +791,7 @@
async resolveStubModuleNameAsync(
from: string,
moduleName: string,
options?: Pick<ResolveModuleConfig, 'conditions'>,
): Promise<string | null> {
const dirname = path.dirname(from);

Expand Down Expand Up @@ -791,6 +820,7 @@
this.getModule(updatedName) ||
(await Resolver.findNodeModuleAsync(updatedName, {
basedir: dirname,
conditions: options?.conditions,
extensions,
moduleDirectory,
paths,
Expand Down
Loading
Loading