Skip to content

Commit

Permalink
fix: big refactor + fixes (mainly cache key + coverage)
Browse files Browse the repository at this point in the history
  • Loading branch information
huafu committed Jul 19, 2018
1 parent 9a2d74f commit e46caae
Show file tree
Hide file tree
Showing 27 changed files with 299 additions and 166 deletions.
11 changes: 0 additions & 11 deletions index.d.ts

This file was deleted.

15 changes: 0 additions & 15 deletions index.js

This file was deleted.

12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
{
"name": "ts-jest",
"version": "23.0.1",
"main": "index.js",
"main": "dist/index.js",
"types": "./dist/index.d.ts",
"description": "A preprocessor with sourcemap support to help use Typescript with Jest",
"scripts": {
"build": "cpx index.d.ts dist/ && tsc -p .",
"build:watch": "cpx index.d.ts dist/ && tsc -p . -w",
"build": "tsc -p tsconfig.build.json",
"build:watch": "tsc -p tsconfig.build.json -w",
"test:nolint": "npm run clean-build && node scripts/tests.js",
"clean": "rimraf dist/**/* && rimraf tests/simple/coverage && rimraf tests/simple-async/coverage && rimraf tests/**/*/debug.txt && rimraf tests/**/node_modules",
"clean": "rimraf dist/**/* && rimraf tests/*/coverage && rimraf tests/*/debug.txt && rimraf tests/*/node_modules",
"clean-build": "npm run clean && npm run build",
"pretest": "npm run tslint && npm run clean-build",
"test": "node scripts/tests.js",
"tslint": "tslint src/*.ts",
"tslint": "tslint src/**/*.ts",
"doc": "doctoc .",
"prepublish": "npm run clean-build",
"precommit": "lint-staged",
Expand All @@ -38,7 +38,7 @@
"homepage": "https://github.com/kulshekhar/ts-jest#readme",
"jest": {
"transform": {
"^.+\\.tsx?$": "<rootDir>/dist/preprocessor.js"
"^.+\\.tsx?$": "<rootDir>/dist/index.js"
},
"testRegex": "tests/__tests__/.*\\.spec\\.ts$",
"testPathIgnorePatterns": [
Expand Down
1 change: 0 additions & 1 deletion preprocessor.js

This file was deleted.

10 changes: 0 additions & 10 deletions scripts/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,6 @@ function createIntegrationMock() {
const rootDir = path.resolve('.');
const testCaseModuleFolder = path.join(testCaseNodeModules, 'ts-jest');

// Copy javascript files
fs.copySync(
path.resolve(rootDir, 'index.js'),
path.resolve(testCaseModuleFolder, 'index.js')
);
fs.copySync(
path.resolve(rootDir, 'preprocessor.js'),
path.resolve(testCaseModuleFolder, 'preprocessor.js')
);

// Copy package.json
fs.copySync(
path.resolve(rootDir, 'package.json'),
Expand Down
35 changes: 35 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// structure of this file heavilly inspired on:
// https://github.com/facebook/jest/blob/master/packages/babel-jest/src/index.js

import jestPreset from 'babel-preset-jest';
import getCacheKeyForArgs from './utils/get-cache-key';
import { TsJestContext, JestCacheKeyArguments } from './types';
import preprocess from './preprocess';

const createTransformer = (options?: any): jest.Transformer => {
const cache = Object.create(null);

options = Object.assign({}, options, {
compact: false,
plugins: (options && options.plugins) || [],
presets: ((options && options.presets) || []).concat([jestPreset]),
sourceMaps: 'both',
});
delete options.cacheDirectory;
delete options.filename;

const context: TsJestContext = { cache, options };

const getCacheKey = (...args: any[]) =>
getCacheKeyForArgs(args as JestCacheKeyArguments, context);

return {
canInstrument: true,
getCacheKey,
process: preprocess,
createTransformer: undefined as any,
};
};

export default createTransformer();
export { createTransformer };
35 changes: 17 additions & 18 deletions src/postprocess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,24 @@ function importBabelDeps() {
istanbulPlugin = require('babel-plugin-istanbul').default;
jestPreset = require('babel-preset-jest');
}
import { CompilerOptions } from 'typescript/lib/typescript';
import { CompilerOptions } from 'typescript';
import {
BabelTransformOptions,
CodeSourceMapPair,
JestConfig,
PostProcessHook,
TransformOptions,
JestCacheKeyOptions,
TsJestConfig,
} from './jest-types';
import { logOnce } from './logger';
} from './types';
import { logOnce } from './utils/logger';

// Function that takes the transpiled typescript and runs it through babel/whatever.
export function postProcessCode(
compilerOptions: CompilerOptions,
jestConfig: JestConfig,
jestConfig: jest.ProjectConfig,
tsJestConfig: TsJestConfig,
transformOptions: TransformOptions,
transpileOutput: CodeSourceMapPair,
transformOptions: jest.TransformOptions,
transpileOutput: jest.TransformedSource,
filePath: string,
): CodeSourceMapPair {
): jest.TransformedSource {
const postHook = getPostProcessHook(
compilerOptions,
jestConfig,
Expand All @@ -58,11 +56,11 @@ function createBabelTransformer(
delete options.filename;

return (
codeSourcemapPair: CodeSourceMapPair,
codeSourcemapPair: jest.TransformedSource,
filename: string,
config: JestConfig,
transformOptions: TransformOptions,
): CodeSourceMapPair => {
config: jest.ProjectConfig,
transformOptions: JestCacheKeyOptions,
): jest.TransformedSource => {
const theseOptions = Object.assign(
{ filename, inputSourceMap: codeSourcemapPair.map },
options,
Expand All @@ -81,17 +79,18 @@ function createBabelTransformer(
],
]);
}
// Babel has incorrect typings, where the map is an object instead of a string. So we have to typecast it here
return (babel.transform(

// we typecast here because babel returns a more complete object than the one expected by jest
return babel.transform(
codeSourcemapPair.code,
theseOptions,
) as any) as CodeSourceMapPair;
) as jest.TransformedSource;
};
}

export const getPostProcessHook = (
tsCompilerOptions: CompilerOptions,
jestConfig: JestConfig,
jestConfig: jest.ProjectConfig,
tsJestConfig: TsJestConfig,
): PostProcessHook => {
if (tsJestConfig.skipBabel) {
Expand Down
43 changes: 7 additions & 36 deletions src/preprocessor.ts → src/preprocess.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,14 @@
import * as crypto from 'crypto';
import {
BabelTransformOptions,
CodeSourceMapPair,
JestConfig,
Path,
TransformOptions,
} from './jest-types';
import { flushLogs, logOnce } from './logger';
import { flushLogs, logOnce } from './utils/logger';
import { postProcessCode } from './postprocess';
import { getTSConfig, getTSJestConfig, runTsDiagnostics } from './utils';
import { transpileTypescript } from './transpiler';

export function process(
export default function preprocess(
src: string,
filePath: Path,
jestConfig: JestConfig,
transformOptions: TransformOptions = { instrument: false },
): CodeSourceMapPair | string {
filePath: jest.Path,
jestConfig: jest.ProjectConfig,
transformOptions: jest.TransformOptions,
): jest.TransformedSource | string {
// transformOptions.instrument is a proxy for collectCoverage
// https://github.com/kulshekhar/ts-jest/issues/201#issuecomment-300572902
const compilerOptions = getTSConfig(jestConfig.globals, jestConfig.rootDir);
Expand All @@ -28,7 +20,7 @@ export function process(
const isHtmlFile = /\.html$/.test(filePath);

// This is to support angular 2. See https://github.com/kulshekhar/ts-jest/pull/145
if (isHtmlFile && jestConfig.globals.__TRANSFORM_HTML__) {
if (isHtmlFile && (jestConfig.globals as any).__TRANSFORM_HTML__) {
src = 'module.exports=' + JSON.stringify(src) + ';';
}

Expand Down Expand Up @@ -76,24 +68,3 @@ export function process(

return { code: outputText.code, map: outputText.map };
}

/**
* This is the function Jest uses to check if it has the file already in cache
*/
export function getCacheKey(
fileData: string,
filePath: Path,
jestConfigStr: string,
transformOptions: TransformOptions = { instrument: false },
): string {
const jestConfig: JestConfig = JSON.parse(jestConfigStr);

const tsConfig = getTSConfig(jestConfig.globals, jestConfig.rootDir);

return crypto
.createHash('md5')
.update(JSON.stringify(tsConfig), 'utf8')
.update(JSON.stringify(transformOptions), 'utf8')
.update(fileData + filePath + jestConfigStr, 'utf8')
.digest('hex');
}
23 changes: 0 additions & 23 deletions src/transpile-if-ts.ts

This file was deleted.

5 changes: 2 additions & 3 deletions src/transpiler.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import * as ts from 'typescript';
import { logOnce } from './logger';
import { CodeSourceMapPair } from './jest-types';
import { logOnce } from './utils/logger';

// Takes the typescript code and by whatever method configured, makes it into javascript code.
export function transpileTypescript(
filePath: string,
fileSrc: string,
compilerOptions: ts.CompilerOptions,
): CodeSourceMapPair {
): jest.TransformedSource {
logOnce('Compiling via normal transpileModule call');
const transpileOutput = transpileViaTranspileModule(
filePath,
Expand Down
38 changes: 16 additions & 22 deletions src/jest-types.ts → src/types.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import { TransformOptions as BabelTransformOpts } from 'babel-core';

export interface TransformOptions {
export interface JestCacheKeyOptions {
rootDir: string;
instrument: boolean;
}

export type Path = string;

export type Glob = string;

export interface ConfigGlobals {
[key: string]: any;
export interface TsJestContext {
cache: any;
options: any;
}

export type JestCacheKeyArguments = [
string,
string,
string,
JestCacheKeyOptions
];

export interface HasteConfig {
defaultPlatform?: string | null;
hasteImplModulePath?: string;
Expand All @@ -24,17 +29,11 @@ export interface BabelTransformOptions extends BabelTransformOpts {
}

export type PostProcessHook = (
codeSourcemapPair: CodeSourceMapPair,
codeSourcemapPair: jest.TransformedSource,
filePath: string,
config: JestConfig,
transformOptions: TransformOptions,
) => CodeSourceMapPair;

export type JestConfig = jest.InitialOptions & {
globals?: jest.ConfigGlobals & {
__TRANSFORM_HTML__?: boolean;
};
};
config: jest.ProjectConfig,
transformOptions: jest.TransformOptions,
) => jest.TransformedSource;

export interface TsJestConfig {
babelConfig?: BabelTransformOpts;
Expand All @@ -53,8 +52,3 @@ export interface JestConfigNormalize {
hasDeprecationWarnings: boolean;
options: jest.DefaultOptions;
}

export interface CodeSourceMapPair {
code: string;
map: string;
}
12 changes: 12 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { readFileSync } from 'fs';
import { resolve } from 'path';

export const BABELRC_FILENAME = '.babelrc';
export const BABELRC_JS_FILENAME = '.babelrc.js';
export const BABEL_CONFIG_KEY = 'babel';
export const TSCONFIG_FILENAME = 'tsconfig.json';
export const TSCONFIG_GLOBALS_KEY = 'ts-jest';
export const PACKAGE_JSON = 'package.json';
export const MY_PACKAGE_CONTENT = readFileSync(
resolve(__dirname, '..', '..', PACKAGE_JSON),
);
Loading

0 comments on commit e46caae

Please sign in to comment.