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

chore: migrate babel-jest to TypeScript #7862

Merged
merged 9 commits into from Feb 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -30,6 +30,7 @@
- `[jest-worker]`: Migrate to TypeScript ([#7853](https://github.com/facebook/jest/pull/7853))
- `[jest-haste-map]`: Migrate to TypeScript ([#7854](https://github.com/facebook/jest/pull/7854))
- `[docs]`: Fix image paths in SnapshotTesting.md for current and version 24 ([#7872](https://github.com/facebook/jest/pull/7872))
- `[babel-jest]`: Migrate to TypeScript ([#7862](https://github.com/facebook/jest/pull/7862))

### Performance

Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/__snapshots__/transform.test.js.snap
Expand Up @@ -6,7 +6,7 @@ FAIL __tests__/ignoredFile.test.js

babel-jest: Babel ignores __tests__/ignoredFile.test.js - make sure to include the file in Jest's transformIgnorePatterns as well.

at loadBabelConfig (../../../packages/babel-jest/build/index.js:134:13)
at loadBabelConfig (../../../packages/babel-jest/build/index.js:133:13)
`;

exports[`babel-jest instruments only specific files and collects coverage 1`] = `
Expand Down
2 changes: 2 additions & 0 deletions packages/babel-jest/package.json
Expand Up @@ -9,7 +9,9 @@
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@jest/types": "^24.1.0",
"babel-plugin-istanbul": "^5.1.0",
"babel-preset-jest": "^24.1.0",
"chalk": "^2.4.2",
Expand Down
Expand Up @@ -4,7 +4,9 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const babelJest = require('../index');

import {Config, Transform} from '@jest/types';
import babelJest from '../index';

//Mock data for all the tests
const sourceString = `
Expand All @@ -24,12 +26,18 @@ const mockConfig = {
};

test(`Returns source string with inline maps when no transformOptions is passed`, () => {
const result = babelJest.process(sourceString, 'dummy_path.js', mockConfig);
const result = babelJest.process(
sourceString,
'dummy_path.js',
(mockConfig as unknown) as Config.ProjectConfig,
) as Transform.TransformedSource;
expect(typeof result).toBe('object');
expect(result.code).toBeDefined();
expect(result.map).toBeDefined();
expect(result.code).toMatch('//# sourceMappingURL');
expect(result.code).toMatch('customMultiply');
// @ts-ignore: it's fine if we get wrong types, the tests will fail then
expect(result.map.sources).toEqual(['dummy_path.js']);
// @ts-ignore: it's fine if we get wrong types, the tests will fail then
expect(JSON.stringify(result.map.sourcesContent)).toMatch('customMultiply');
});
Expand Up @@ -3,32 +3,31 @@
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import type {Path, ProjectConfig} from 'types/Config';
import type {
CacheKeyOptions,
Transformer,
TransformOptions,
TransformedSource,
} from 'types/Transform';

import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import {transformSync as babelTransform, loadPartialConfig} from '@babel/core';
import {Config, Transform} from '@jest/types';
import {
transformSync as babelTransform,
loadPartialConfig,
TransformOptions,
PartialConfig,
} from '@babel/core';
import chalk from 'chalk';
import slash from 'slash';

const THIS_FILE = fs.readFileSync(__filename);
const jestPresetPath = require.resolve('babel-preset-jest');
const babelIstanbulPlugin = require.resolve('babel-plugin-istanbul');

const createTransformer = (options: any): Transformer => {
const createTransformer = (
options: TransformOptions = {},
): Transform.Transformer => {
options = {
...options,
// @ts-ignore: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/32955
caller: {
name: 'babel-jest',
supportsStaticESM: false,
Expand All @@ -39,10 +38,10 @@ const createTransformer = (options: any): Transformer => {
sourceMaps: 'both',
};

delete options.cacheDirectory;
delete options.filename;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overwritten on line 47 anyways


function loadBabelConfig(cwd, filename) {
function loadBabelConfig(
cwd: Config.Path,
filename: Config.Path,
): PartialConfig {
// `cwd` first to allow incoming options to override it
const babelConfig = loadPartialConfig({cwd, ...options, filename});

Expand All @@ -63,9 +62,13 @@ const createTransformer = (options: any): Transformer => {
canInstrument: true,
getCacheKey(
fileData: string,
filename: Path,
filename: Config.Path,
configString: string,
{config, instrument, rootDir}: {config: ProjectConfig} & CacheKeyOptions,
{
config,
instrument,
rootDir,
}: {config: Config.ProjectConfig} & Transform.CacheKeyOptions,
): string {
const babelOptions = loadBabelConfig(config.cwd, filename);
const configPath = [
Expand Down Expand Up @@ -96,16 +99,16 @@ const createTransformer = (options: any): Transformer => {
},
process(
src: string,
filename: Path,
config: ProjectConfig,
transformOptions?: TransformOptions,
): string | TransformedSource {
filename: Config.Path,
config: Config.ProjectConfig,
transformOptions?: Transform.TransformOptions,
): string | Transform.TransformedSource {
const babelOptions = {...loadBabelConfig(config.cwd, filename).options};

if (transformOptions && transformOptions.instrument) {
babelOptions.auxiliaryCommentBefore = ' istanbul ignore next ';
// Copied from jest-runtime transform.js
babelOptions.plugins = babelOptions.plugins.concat([
babelOptions.plugins = (babelOptions.plugins || []).concat([
[
babelIstanbulPlugin,
{
Expand All @@ -119,10 +122,23 @@ const createTransformer = (options: any): Transformer => {

const transformResult = babelTransform(src, babelOptions);

return transformResult || src;
if (transformResult) {
const {code, map} = transformResult;
if (typeof code === 'string') {
return {code, map};
}
}

return src;
},
};
};

module.exports = createTransformer();
(module.exports: any).createTransformer = createTransformer;
const transformer = createTransformer();

// FIXME: This is not part of the exported TS types. When fixed, remember to
// move @types/babel__core to `dependencies` instead of `devDependencies`
// (one fix is to use ESM, maybe for Jest 25?)
transformer.createTransformer = createTransformer;

export = transformer;
9 changes: 9 additions & 0 deletions packages/babel-jest/tsconfig.json
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "build"
},
// TODO: include `babel-preset-jest` even though we don't care about its types
"references": [{"path": "../jest-types"}]
SimenB marked this conversation as resolved.
Show resolved Hide resolved
}
5 changes: 4 additions & 1 deletion packages/jest-types/package.json
Expand Up @@ -11,5 +11,8 @@
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts"
"types": "build/index.d.ts",
"dependencies": {
"source-map": "^0.6.1"
}
}
59 changes: 59 additions & 0 deletions packages/jest-types/src/Transform.ts
@@ -0,0 +1,59 @@
/**
* 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 {Script} from 'vm';
import {RawSourceMap} from 'source-map';
import {Path, ProjectConfig} from './Config';

// https://stackoverflow.com/a/48216010/1850276
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

// This is fixed in a newer version, but that depends on Node 8 which is a
// breaking change (engine warning when installing)
interface FixedRawSourceMap extends Omit<RawSourceMap, 'version'> {
version: number;
}

export type TransformedSource = {
code: string;
map?: FixedRawSourceMap | string | null;
};

export type TransformResult = {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this type is not use now - it will be by jest-runtime later, though

script: Script;
mapCoverage: boolean;
sourceMapPath?: string;
};

export type TransformOptions = {
instrument: boolean;
};

export type CacheKeyOptions = {
config: ProjectConfig;
instrument: boolean;
rootDir: string;
};

export type Transformer = {
canInstrument?: boolean;
createTransformer?: (options: any) => Transformer;

getCacheKey: (
fileData: string,
filePath: Path,
configStr: string,
options: CacheKeyOptions,
) => string;

process: (
sourceText: string,
sourcePath: Path,
config: ProjectConfig,
options?: TransformOptions,
) => string | TransformedSource;
};
3 changes: 2 additions & 1 deletion packages/jest-types/src/index.ts
Expand Up @@ -10,5 +10,6 @@ import * as Console from './Console';
import * as SourceMaps from './SourceMaps';
import * as TestResult from './TestResult';
import * as Mocks from './Mocks';
import * as Transform from './Transform';

export {Config, Console, SourceMaps, TestResult, Mocks};
export {Config, Console, SourceMaps, TestResult, Mocks, Transform};