Skip to content

Commit

Permalink
Add option to define a custom resolver (jestjs#2998)
Browse files Browse the repository at this point in the history
* Add option to define a custom resolver

* Add documentation for resolver config option

* Add test for when overriding default resolver

* Made it more clear in the docs what resolver is expected to return
  • Loading branch information
dlmr authored and skovhus committed Apr 29, 2017
1 parent 9e92ab4 commit 692af13
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 5 deletions.
17 changes: 17 additions & 0 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,23 @@ Default: `false`

If enabled, the module registry for every test file will be reset before running each individual test. This is useful to isolate modules for every test so that local module state doesn't conflict between tests. This can be done programmatically using [`jest.resetModules()`](#jest-resetmodules).

### `resolver` [string]
Default: `undefined`

This option allows the use of a custom resolver. This resolver must be a node module that exports a function expecting a string as the first argument for the path to resolve and an object with the following structure as the second argument:

```
{
"basedir": string,
"browser": bool,
"extensions": [string],
"moduleDirectory": [string],
"paths": [string]
}
```

The function should either return a path to the module that should be resolved or throw an error if the module can't be found.

### `rootDir` [string]
Default: The root of the directory containing the `package.json` *or* the [`pwd`](http://en.wikipedia.org/wiki/Pwd) if no `package.json` is found

Expand Down
1 change: 1 addition & 0 deletions packages/jest-config/src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ function normalize(config: InitialConfig, argv: Object = {}) {
break;
case 'setupTestFrameworkScriptFile':
case 'testResultsProcessor':
case 'resolver':
//$FlowFixMe
value = resolve(config.rootDir, key, config[key]);
break;
Expand Down
1 change: 1 addition & 0 deletions packages/jest-config/src/validConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ module.exports = ({
preset: 'react-native',
resetMocks: false,
resetModules: false,
resolver: '<rootDir>/resolver.js',
rootDir: '/',
roots: ['<rootDir>'],
setupFiles: ['<rootDir>/setup.js'],
Expand Down
13 changes: 13 additions & 0 deletions packages/jest-resolve/src/__mocks__/userResolver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/

'use strict';

module.exports = function userResolver(path, options) {
return 'module';
};
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

'use strict';

const path = require('path');
const ModuleMap = require('jest-haste-map').ModuleMap;
const Resolver = require('../');

Expand Down Expand Up @@ -37,3 +38,34 @@ describe('isCoreModule', () => {
expect(isCore).toEqual(false);
});
});

describe('findNodeModule', () => {
it('is possible to override the default resolver', () => {
const nodePaths = process.env.NODE_PATH
? process.env.NODE_PATH.split(path.delimiter)
: null;

jest.mock('../__mocks__/userResolver');
const userResolver = require('../__mocks__/userResolver');
userResolver.mockImplementation(() => 'module');

const newPath = Resolver.findNodeModule('test', {
basedir: '/',
browser: true,
extensions: ['js'],
moduleDirectory: ['node_modules'],
paths: ['/something'],
resolver: require.resolve('../__mocks__/userResolver'),
});

expect(newPath).toBe('module');
expect(userResolver.mock.calls[0][0]).toBe('test');
expect(userResolver.mock.calls[0][1]).toEqual({
basedir: '/',
browser: true,
extensions: ['js'],
moduleDirectory: ['node_modules'],
paths: (nodePaths || []).concat(['/something']),
});
});
});
40 changes: 40 additions & 0 deletions packages/jest-resolve/src/defaultResolver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/

'use strict';

import type {Path} from 'types/Config';

const resolve = require('resolve');
const browserResolve = require('browser-resolve');

type ResolverOptions = {|
basedir: Path,
browser?: boolean,
extensions?: Array<string>,
moduleDirectory?: Array<string>,
paths?: ?Array<Path>,
|};

function defaultResolver(path: Path, options: ResolverOptions) {
const resv = options.browser ? browserResolve : resolve;

return resv.sync(
path,
{
basedir: options.basedir,
extensions: options.extensions,
moduleDirectory: options.moduleDirectory,
paths: options.paths,
}
);
}

module.exports = defaultResolver;
14 changes: 9 additions & 5 deletions packages/jest-resolve/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ import type {ModuleMap} from 'types/HasteMap';

const nodeModulesPaths = require('resolve/lib/node-modules-paths');
const path = require('path');
const resolve = require('resolve');
const browserResolve = require('browser-resolve');
const isBuiltinModule = require('is-builtin-module');

type ResolverConfig = {|
Expand All @@ -28,6 +26,7 @@ type ResolverConfig = {|
moduleNameMapper: ?Array<ModuleNameMapperConfig>,
modulePaths: Array<Path>,
platforms?: Array<string>,
resolver: ?Path,
|};

type FindNodeModuleConfig = {|
Expand All @@ -36,6 +35,7 @@ type FindNodeModuleConfig = {|
extensions?: Array<string>,
moduleDirectory?: Array<string>,
paths?: Array<Path>,
resolver?: ?Path,
|};

type ModuleNameMapperConfig = {|
Expand Down Expand Up @@ -73,6 +73,7 @@ class Resolver {
moduleNameMapper: options.moduleNameMapper,
modulePaths: options.modulePaths,
platforms: options.platforms,
resolver: options.resolver,
};
this._moduleMap = moduleMap;
this._moduleIDCache = Object.create(null);
Expand All @@ -81,13 +82,15 @@ class Resolver {
}

static findNodeModule(path: Path, options: FindNodeModuleConfig): ?Path {
/* $FlowFixMe */
const resolver = require(options.resolver || './defaultResolver.js');
const paths = options.paths;

try {
const resv = options.browser ? browserResolve : resolve;
return resv.sync(
path,
return resolver(path,
{
basedir: options.basedir,
browser: options.browser,
extensions: options.extensions,
moduleDirectory: options.moduleDirectory,
paths: paths ? (nodePaths || []).concat(paths) : nodePaths,
Expand Down Expand Up @@ -145,6 +148,7 @@ class Resolver {
extensions,
moduleDirectory,
paths,
resolver: this._options.resolver,
});

if (module) {
Expand Down
1 change: 1 addition & 0 deletions packages/jest-runtime/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ class Runtime {
moduleNameMapper: getModuleNameMapper(config),
modulePaths: config.modulePaths,
platforms: config.haste.platforms,
resolver: config.resolver,
});
}

Expand Down
2 changes: 2 additions & 0 deletions types/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export type Config = {|
preset: ?string,
resetMocks: boolean,
resetModules: boolean,
resolver: ?Path,
rootDir: Path,
roots: Array<Path>,
setupFiles: Array<Path>,
Expand Down Expand Up @@ -151,6 +152,7 @@ export type InitialConfig = {|
preset?: ?string,
resetMocks?: boolean,
resetModules?: boolean,
resolver?: ?Path,
rootDir: Path,
roots?: Array<Path>,
scriptPreprocessor?: string,
Expand Down

0 comments on commit 692af13

Please sign in to comment.