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

Allow JSON transforms #8278

Merged
merged 11 commits into from
Apr 11, 2019
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Fixes

- `[jest-snapshot]` Inline snapshots: do not indent empty lines ([#8277](https://github.com/facebook/jest/pull/8277))
- `[@jest/runtime, @jest/transform]` Allow custom transforms for JSON dependencies ([#2578](https://github.com/facebook/jest/pull/2578))
- `[jest-core]` Make `detectOpenHandles` imply `runInBand` ([#8283](https://github.com/facebook/jest/pull/8283))

### Chore & Maintenance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,29 @@ describe('Runtime', () => {
const exports = runtime.requireInternalModule(modulePath);
expect(exports()).toBe('internal-module-data');
}));

it('loads JSON modules and applies transforms', () =>
createRuntime(__filename, {
transform: {'^.+\\.json$': './test_json_preprocessor'},
}).then(runtime => {
const modulePath = path.resolve(
path.dirname(runtime.__mockRootPath),
'internal-root.json',
);
const exports = runtime.requireModule(modulePath);
expect(exports).toEqual({foo: 'foo'});
}));

it('loads internal JSON modules without applying transforms', () =>
createRuntime(__filename, {
transform: {'^.+\\.json$': './test_json_preprocessor'},
}).then(runtime => {
const modulePath = path.resolve(
path.dirname(runtime.__mockRootPath),
'internal-root.json',
);
const exports = runtime.requireInternalModule(modulePath);
expect(exports).toEqual({foo: 'bar'});
}));
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"foo": "bar"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* 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.
*/

'use strict';

module.exports.process = source => {
const json = JSON.parse(source);
Object.keys(json).forEach(k => (json[k] = k));
return JSON.stringify(json);
};
34 changes: 24 additions & 10 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
ScriptTransformer,
ShouldInstrumentOptions,
shouldInstrument,
TransformationOptions,
} from '@jest/transform';
import fs from 'graceful-fs';
import stripBOM from 'strip-bom';
Expand Down Expand Up @@ -465,8 +466,16 @@ class Runtime {
moduleRegistry: ModuleRegistry,
) {
if (path.extname(modulePath) === '.json') {
const text = stripBOM(fs.readFileSync(modulePath, 'utf8'));

const transformedFile = this._scriptTransformer.transformJson(
modulePath,
this._getFullTransformationOptions(options),
text,
);

localModule.exports = this._environment.global.JSON.parse(
stripBOM(fs.readFileSync(modulePath, 'utf8')),
MLoughry marked this conversation as resolved.
Show resolved Hide resolved
transformedFile,
);
} else if (path.extname(modulePath) === '.node') {
localModule.exports = require(modulePath);
Expand All @@ -478,6 +487,19 @@ class Runtime {
localModule.loaded = true;
}

private _getFullTransformationOptions(
options: InternalModuleOptions | undefined,
): TransformationOptions {
return {
...options,
changedFiles: this._coverageOptions.changedFiles,
collectCoverage: this._coverageOptions.collectCoverage,
collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
extraGlobals: this._config.extraGlobals || [],
};
}

requireModuleOrMock(from: Config.Path, moduleName: string) {
try {
if (this._shouldMock(from, moduleName)) {
Expand Down Expand Up @@ -676,7 +698,6 @@ class Runtime {
return;
}

const isInternalModule = !!(options && options.isInternalModule);
const filename = localModule.filename;
const lastExecutingModulePath = this._currentlyExecutingModulePath;
this._currentlyExecutingModulePath = filename;
Expand All @@ -701,14 +722,7 @@ class Runtime {
const extraGlobals = this._config.extraGlobals || [];
const transformedFile = this._scriptTransformer.transform(
filename,
{
changedFiles: this._coverageOptions.changedFiles,
collectCoverage: this._coverageOptions.collectCoverage,
collectCoverageFrom: this._coverageOptions.collectCoverageFrom,
collectCoverageOnlyFrom: this._coverageOptions.collectCoverageOnlyFrom,
extraGlobals,
isInternalModule,
},
this._getFullTransformationOptions(options),
this._cacheFS[filename],
);

Expand Down
22 changes: 22 additions & 0 deletions packages/jest-transform/src/ScriptTransformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,28 @@ export default class ScriptTransformer {
return result;
}

transformJson(
filename: Config.Path,
options: Options,
fileSource: string,
): string {
const isInternalModule = options.isInternalModule;
const isCoreModule = options.isCoreModule;
const willTransform =
!isInternalModule && !isCoreModule && this.shouldTransform(filename);

if (willTransform) {
const {code: transformedJsonSource} = this.transformSource(
filename,
fileSource,
false,
);
return transformedJsonSource;
}

return fileSource;
}

/**
* @deprecated use `this.shouldTransform` instead
*/
Expand Down
6 changes: 5 additions & 1 deletion packages/jest-transform/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,8 @@

export {default as ScriptTransformer} from './ScriptTransformer';
export {default as shouldInstrument} from './shouldInstrument';
export {Transformer, ShouldInstrumentOptions} from './types';
export {
Transformer,
ShouldInstrumentOptions,
Options as TransformationOptions,
} from './types';