diff --git a/.editorconfig b/.editorconfig index 639cce3aa0..0a6cd765d8 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,5 +7,8 @@ end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true -[*.md,*.snap] +[*.md] +trim_trailing_whitespace = false + +[*.snap] trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore index 6bf7fdc08f..bc66b30bc2 100644 --- a/.gitignore +++ b/.gitignore @@ -43,13 +43,14 @@ jspm_packages .vscode .idea - +.cache # tests specific tests/simple-long-path/long-src-path # is linked to the temp dir of the os e2e/__workdir_synlink__ **/.ts-jest-e2e.json +.ts-jest-digest # while refactoring... old/ diff --git a/.npmignore b/.npmignore index 9168b0e8cf..807d8ccce6 100644 --- a/.npmignore +++ b/.npmignore @@ -69,8 +69,12 @@ tsconfig.build.json tslint.json .npmrc .markdownlint.yaml +.cache # Github Pages docs commitlint.config.js + +# ensure we do not omit the digest +!.ts-jest-digest diff --git a/.travis.yml b/.travis.yml index ebc1a548a3..40686a9023 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,7 @@ env: cache: npm: true directories: + - .cache - /tmp/ts-jest-e2e-workdir/__templates__ node_js: @@ -36,9 +37,9 @@ script: # only grab coverage data on node 10 - | if [[ "$(node --version)" == v10.* ]]; then - npm run test -- --coverage; + npm run test -- --runInBand --coverage; else - npm run test; + npm run test -- --runInBand; fi after_success: diff --git a/appveyor.yml b/appveyor.yml index adc381521a..7610f4e0f9 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -21,19 +21,20 @@ install: - ps: Install-Product node 8 x64 - npm install -g npm@^5 # Typical npm stuff. - - set CI=true + # - set CI=true # Our E2E work dir - set TS_JEST_E2E_WORKDIR=%APPDATA%\ts-jest-e2e - npm ci --ignore-scripts - npm run clean -- --when-ci-commit-message cache: + - .cache -> package.json - '%APPDATA%\npm-cache' - '%APPDATA%\ts-jest-e2e\__templates__' # Post-install test scripts. test_script: - - cmd: npm run test + - cmd: npm run test -- --runInBand # skip_commits: # files: diff --git a/e2e/__cases__/deep/src/Tests/jest.config.js b/e2e/__cases__/deep/src/Tests/jest.config.js index 3ad00da01c..5f8f09a3cc 100755 --- a/e2e/__cases__/deep/src/Tests/jest.config.js +++ b/e2e/__cases__/deep/src/Tests/jest.config.js @@ -20,5 +20,4 @@ module.exports = Object.assign({}, cfg, { tsConfig: "./tsconfig.json", }, }, - // testResultsProcessor: "jest-teamcity-reporter", }) diff --git a/e2e/__cases__/ts-jest-checks/index.spec.ts b/e2e/__cases__/ts-jest-checks/index.spec.ts new file mode 100644 index 0000000000..2ea1f32ce1 --- /dev/null +++ b/e2e/__cases__/ts-jest-checks/index.spec.ts @@ -0,0 +1,12 @@ +import { createTransformer } from 'ts-jest' +import { readFileSync } from 'fs' + +describe('tsConfig', () => { + it('should have digest and versions', () => { + const tr = createTransformer() + const cs = tr.configsFor({} as any) + expect(cs.tsJestDigest).toHaveLength(40) + expect(cs.tsJestDigest).toBe(readFileSync(require.resolve('ts-jest/.ts-jest-digest'), 'utf8')) + expect(cs.versions['ts-jest']).toBe(require('ts-jest/package.json').version) + }) +}) diff --git a/e2e/__helpers__/test-case/run-result.ts b/e2e/__helpers__/test-case/run-result.ts index f37ec02a08..ca80a640e5 100644 --- a/e2e/__helpers__/test-case/run-result.ts +++ b/e2e/__helpers__/test-case/run-result.ts @@ -4,6 +4,8 @@ import { readFileSync, realpathSync } from 'fs' import { tmpdir } from 'os' import { resolve, sep } from 'path' +import { cacheDir } from '../../../scripts/lib/paths' + import ProcessedFileIo from './processed-file-io' import { escapeRegex, normalizeJestOutput, stripAnsiColors } from './utils' @@ -17,6 +19,7 @@ export default class RunResult { cmd: string args: string[] env: { [key: string]: string } + config: jest.InitialOptions }>, ) {} get logFilePath() { @@ -56,9 +59,11 @@ export default class RunResult { return normalizeJestOutput(this.stdout) } get cmdLine() { - return [this.context.cmd, ...this.context.args] - .filter(a => !['-u', '--updateSnapshot', '--runInBand', '--'].includes(a)) - .join(' ') + return this.normalize( + [this.context.cmd, ...this.context.args] + .filter(a => !['-u', '--updateSnapshot', '--runInBand', '--'].includes(a)) + .join(' '), + ) } ioFor(relFilePath: string): ProcessedFileIo { @@ -80,7 +85,12 @@ export default class RunResult { const realCwd = realpathSync(cwd) const tmp = tmpdir() const realTmp = realpathSync(tmp) - const map = [{ from: cwd, to: '' }, { from: tmp, to: '' }, { from: /\b[a-f0-9]{40}\b/g, to: '' }] + const map = [ + { from: cwd, to: '' }, + { from: tmp, to: '' }, + { from: /\b[a-f0-9]{40}\b/g, to: '' }, + { from: cacheDir, to: '' }, + ] if (cwd !== realCwd) map.push({ from: realCwd, to: '' }) if (tmp !== realTmp) map.push({ from: realTmp, to: '' }) if (sep === '\\') { diff --git a/e2e/__helpers__/test-case/runtime.ts b/e2e/__helpers__/test-case/runtime.ts index b31ce8bf9f..c4eb2b5684 100644 --- a/e2e/__helpers__/test-case/runtime.ts +++ b/e2e/__helpers__/test-case/runtime.ts @@ -16,7 +16,7 @@ import { writeFileSync, } from 'fs-extra' import merge from 'lodash.merge' -import { join, relative, sep } from 'path' +import { join, relative, resolve, sep } from 'path' import * as Paths from '../../../scripts/lib/paths' @@ -49,19 +49,35 @@ function hooksSourceWith(vars: Record): string { } export function run(name: string, options: RunTestOptions = {}): RunResult { - const { args = [], env = {}, template, inject, writeIo } = options + const { + args = [], + env = {}, + template, + inject, + writeIo, + noCache, + jestConfigPath: configFile = 'jest.config.js', + } = options const { workdir: dir, sourceDir, hooksFile, ioDir } = prepareTest( name, template || templateNameForPath(join(Paths.e2eSourceDir, name)), options, ) - const pkg = require(join(dir, 'package.json')) + const pkg = readJsonSync(join(dir, 'package.json')) + + // grab base configuration + const jestConfigPath = resolve(dir, configFile) + let baseConfig: jest.InitialOptions = require(jestConfigPath) + if (configFile === 'package.json') baseConfig = (baseConfig as any).jest + + const extraConfig = {} as jest.InitialOptions let shortCmd: string let cmdArgs: string[] = [] if (inject) { - cmdArgs.push('--testPathPattern="/__eval\\\\.ts$"') - } // '--testRegex=""' + extraConfig.testMatch = undefined + extraConfig.testRegex = '/__eval\\.ts$' + } if (process.argv.find(v => ['--updateSnapshot', '-u'].includes(v))) { cmdArgs.push('-u') } @@ -77,25 +93,42 @@ export function run(name: string, options: RunTestOptions = {}): RunResult { shortCmd = 'jest' } - // merge given config extend - if (options.jestConfig || options.tsJestConfig) { - let originalConfig: any = join(dir, 'jest.config.js') - if (existsSync(originalConfig)) { - originalConfig = require(originalConfig) + // check/merge config + if (cmdArgs.includes('--config')) { + throw new Error(`Extend config using tsJestConfig and jestConfig options, not thru args.`) + } + if (cmdArgs.includes('--no-cache')) { + throw new Error(`Use the noCache option to disable cache, not thru args.`) + } + // extends config + if (options.jestConfig) { + merge(extraConfig, options.jestConfig) + } + if (options.tsJestConfig) { + const globalConfig: any = extraConfig.globals || (extraConfig.globals = {}) + const tsJestConfig = globalConfig['ts-jest'] || (globalConfig['ts-jest'] = {}) + merge(tsJestConfig, options.tsJestConfig) + } + + if (noCache || writeIo) { + cmdArgs.push('--no-cache') + } else if (!(baseConfig.cacheDirectory || extraConfig.cacheDirectory)) { + // force the cache directory if not set + extraConfig.cacheDirectory = join(Paths.cacheDir, `e2e-${template}`) + } + + // write final config + const finalConfig = merge({}, baseConfig, extraConfig) + if (Object.keys(extraConfig).length !== 0) { + if (configFile === 'package.json') { + pkg.jest = finalConfig + outputJsonSync(jestConfigPath, pkg) } else { - originalConfig = require(join(dir, 'package.json')).jest || {} + outputFileSync(jestConfigPath, `module.exports = ${JSON.stringify(finalConfig, null, 2)}`, 'utf8') } - cmdArgs.push( - '--config', - JSON.stringify( - merge({}, originalConfig, options.jestConfig, { - globals: { 'ts-jest': options.tsJestConfig || {} }, - }), - ), - ) } - // run in band + // ensure we run in band if (!cmdArgs.includes('--runInBand')) { cmdArgs.push('--runInBand') } @@ -142,6 +175,7 @@ export function run(name: string, options: RunTestOptions = {}): RunResult { args: cmdArgs, env: mergedEnv, ioDir: writeIo ? ioDir : undefined, + config: finalConfig, }) } diff --git a/e2e/__helpers__/test-case/types.ts b/e2e/__helpers__/test-case/types.ts index 3bba78e2f5..3df848b707 100644 --- a/e2e/__helpers__/test-case/types.ts +++ b/e2e/__helpers__/test-case/types.ts @@ -10,6 +10,8 @@ export interface RunTestOptions { writeIo?: boolean jestConfig?: jest.ProjectConfig | any tsJestConfig?: TsJestConfig | any + noCache?: boolean + jestConfigPath?: string } export type RunWithTemplatesIterator = (runtTest: () => RunResult, context: RunWithTemplateIteratorContext) => void diff --git a/e2e/__tests__/__snapshots__/diagnostics.test.ts.snap b/e2e/__tests__/__snapshots__/diagnostics.test.ts.snap index 9f64c55c43..7be8b505c4 100644 --- a/e2e/__tests__/__snapshots__/diagnostics.test.ts.snap +++ b/e2e/__tests__/__snapshots__/diagnostics.test.ts.snap @@ -116,7 +116,7 @@ exports[`With diagnostics, first throws should fail using template "with-typescr `; exports[`With diagnostics, warn only should pass using template "default" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"diagnostics":{"warnOnly":true}}}} + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -138,7 +138,7 @@ exports[`With diagnostics, warn only should pass using template "default" 1`] = `; exports[`With diagnostics, warn only should pass using template "with-babel-6" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"babelConfig":true,"diagnostics":{"warnOnly":true}}}} + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -160,7 +160,7 @@ exports[`With diagnostics, warn only should pass using template "with-babel-6" 1 `; exports[`With diagnostics, warn only should pass using template "with-babel-7" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"babelConfig":true,"diagnostics":{"warnOnly":true}}}} + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -182,7 +182,7 @@ exports[`With diagnostics, warn only should pass using template "with-babel-7" 1 `; exports[`With diagnostics, warn only should pass using template "with-jest-22" 1`] = ` - √ jest --config {"transform":{"^.+\\\\.tsx?$":"ts-jest"},"testMatch":["**/__tests__/**/*.js?(x)","**/?(*.)+(spec|test).js?(x)","**/__tests__/**/*.ts?(x)","**/?(*.)+(spec|test).ts?(x)"],"moduleFileExtensions":["js","json","jsx","node","ts","tsx"],"testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"diagnostics":{"warnOnly":true}}}} + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -204,7 +204,7 @@ exports[`With diagnostics, warn only should pass using template "with-jest-22" 1 `; exports[`With diagnostics, warn only should pass using template "with-typescript-2-7" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"diagnostics":{"ignoreCodes":[5023],"warnOnly":true}}}} + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== diff --git a/e2e/__tests__/__snapshots__/hoisting.test.ts.snap b/e2e/__tests__/__snapshots__/hoisting.test.ts.snap index 7c4099282b..fcbf5639d3 100644 --- a/e2e/__tests__/__snapshots__/hoisting.test.ts.snap +++ b/e2e/__tests__/__snapshots__/hoisting.test.ts.snap @@ -58,7 +58,7 @@ exports[`Hoisting jest.mock() & jest.unmock() should pass using template "defaul `; exports[`Hoisting jest.mock() & jest.unmock() should pass using template "default": output 1`] = ` - √ jest + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -134,7 +134,7 @@ exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-b `; exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-babel-6": output 1`] = ` - √ jest + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -218,7 +218,7 @@ exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-b `; exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-babel-7": output 1`] = ` - √ jest + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -293,7 +293,7 @@ exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-j `; exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-jest-22": output 1`] = ` - √ jest + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -368,7 +368,7 @@ exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-t `; exports[`Hoisting jest.mock() & jest.unmock() should pass using template "with-typescript-2-7": output 1`] = ` - √ jest + √ jest --no-cache ↳ exit code: 0 ===[ STDOUT ]=================================================================== diff --git a/e2e/__tests__/__snapshots__/isolated-modules.test.ts.snap b/e2e/__tests__/__snapshots__/isolated-modules.test.ts.snap index ae5954b391..f744686504 100644 --- a/e2e/__tests__/__snapshots__/isolated-modules.test.ts.snap +++ b/e2e/__tests__/__snapshots__/isolated-modules.test.ts.snap @@ -1,7 +1,7 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`With isolatedModules enabled should pass using template "default" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"isolatedModules":true}}} + √ jest ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -18,7 +18,7 @@ exports[`With isolatedModules enabled should pass using template "default" 1`] = `; exports[`With isolatedModules enabled should pass using template "with-babel-6" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"babelConfig":true,"isolatedModules":true}}} + √ jest ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -35,7 +35,7 @@ exports[`With isolatedModules enabled should pass using template "with-babel-6" `; exports[`With isolatedModules enabled should pass using template "with-babel-7" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"babelConfig":true,"isolatedModules":true}}} + √ jest ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -52,7 +52,7 @@ exports[`With isolatedModules enabled should pass using template "with-babel-7" `; exports[`With isolatedModules enabled should pass using template "with-jest-22" 1`] = ` - √ jest --config {"transform":{"^.+\\\\.tsx?$":"ts-jest"},"testMatch":["**/__tests__/**/*.js?(x)","**/?(*.)+(spec|test).js?(x)","**/__tests__/**/*.ts?(x)","**/?(*.)+(spec|test).ts?(x)"],"moduleFileExtensions":["js","json","jsx","node","ts","tsx"],"testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"isolatedModules":true}}} + √ jest ↳ exit code: 0 ===[ STDOUT ]=================================================================== @@ -69,7 +69,7 @@ exports[`With isolatedModules enabled should pass using template "with-jest-22" `; exports[`With isolatedModules enabled should pass using template "with-typescript-2-7" 1`] = ` - √ jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"diagnostics":{"ignoreCodes":[5023]},"isolatedModules":true}}} + √ jest ↳ exit code: 0 ===[ STDOUT ]=================================================================== diff --git a/e2e/__tests__/__snapshots__/logger.test.ts.snap b/e2e/__tests__/__snapshots__/logger.test.ts.snap index 5cf91db511..97c29db22f 100644 --- a/e2e/__tests__/__snapshots__/logger.test.ts.snap +++ b/e2e/__tests__/__snapshots__/logger.test.ts.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`TS_JEST_LOG should pass and create log file when using tempalte "default" 1`] = ` +exports[`TS_JEST_LOG should pass and create log file when using template "default" 1`] = ` Array [ "[level:20] creating jest presets not handling JavaScript files", "[level:20] creating Importer singleton", @@ -20,26 +20,24 @@ Array [ "[level:20] normalized typescript config", "[level:20] processing /Hello.spec.ts", "[level:20] creating typescript compiler (language service)", - "[level:20] will use file caching", + "[level:20] file caching disabled", "[level:20] creating language service", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", "[level:20] computing cache key for /Hello.ts", "[level:20] processing /Hello.ts", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", ] `; -exports[`TS_JEST_LOG should pass and create log file when using tempalte "with-babel-6" 1`] = ` +exports[`TS_JEST_LOG should pass and create log file when using template "with-babel-6" 1`] = ` Array [ "[level:20] creating jest presets not handling JavaScript files", "[level:20] creating Importer singleton", @@ -68,28 +66,26 @@ Array [ "[level:20] patching babel-jest", "[level:20] checking version of babel-jest: OK", "[level:20] creating typescript compiler (language service)", - "[level:20] will use file caching", + "[level:20] file caching disabled", "[level:20] creating language service", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", "[level:20] calling babel-jest processor", "[level:20] computing cache key for /Hello.ts", "[level:20] processing /Hello.ts", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", "[level:20] calling babel-jest processor", ] `; -exports[`TS_JEST_LOG should pass and create log file when using tempalte "with-babel-7" 1`] = ` +exports[`TS_JEST_LOG should pass and create log file when using template "with-babel-7" 1`] = ` Array [ "[level:20] creating jest presets not handling JavaScript files", "[level:20] creating Importer singleton", @@ -117,28 +113,26 @@ Array [ "[level:20] patching babel-jest", "[level:20] checking version of babel-jest: OK", "[level:20] creating typescript compiler (language service)", - "[level:20] will use file caching", + "[level:20] file caching disabled", "[level:20] creating language service", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", "[level:20] calling babel-jest processor", "[level:20] computing cache key for /Hello.ts", "[level:20] processing /Hello.ts", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", "[level:20] calling babel-jest processor", ] `; -exports[`TS_JEST_LOG should pass and create log file when using tempalte "with-jest-22" 1`] = ` +exports[`TS_JEST_LOG should pass and create log file when using template "with-jest-22" 1`] = ` Array [ "[level:20] creating Importer singleton", "[level:20] creating jest presets not handling JavaScript files", @@ -157,26 +151,24 @@ Array [ "[level:20] normalized typescript config", "[level:20] processing /Hello.spec.ts", "[level:20] creating typescript compiler (language service)", - "[level:20] will use file caching", + "[level:20] file caching disabled", "[level:20] creating language service", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", "[level:20] computing cache key for /Hello.ts", "[level:20] processing /Hello.ts", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", ] `; -exports[`TS_JEST_LOG should pass and create log file when using tempalte "with-typescript-2-7" 1`] = ` +exports[`TS_JEST_LOG should pass and create log file when using template "with-typescript-2-7" 1`] = ` Array [ "[level:20] creating jest presets not handling JavaScript files", "[level:20] creating Importer singleton", @@ -196,22 +188,20 @@ Array [ "[level:20] normalized typescript config", "[level:20] processing /Hello.spec.ts", "[level:20] creating typescript compiler (language service)", - "[level:20] will use file caching", + "[level:20] file caching disabled", "[level:20] creating language service", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", "[level:20] computing cache key for /Hello.ts", "[level:20] processing /Hello.ts", - "[level:20] readThrough(): cache miss", + "[level:20] readThrough(): no cache", "[level:20] getOutput(): compiling using language service", "[level:20] updateMemoryCache()", "[level:20] visitSourceFileNode(): hoisting", "[level:20] getOutput(): computing diagnostics", - "[level:20] readThrough(): writing caches", ] `; diff --git a/e2e/__tests__/__snapshots__/simple.test.ts.snap b/e2e/__tests__/__snapshots__/simple.test.ts.snap deleted file mode 100644 index 94d0438d92..0000000000 --- a/e2e/__tests__/__snapshots__/simple.test.ts.snap +++ /dev/null @@ -1,91 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Simple test should pass using template "default" 1`] = ` - √ jest - ↳ exit code: 0 - ===[ STDOUT ]=================================================================== - - ===[ STDERR ]=================================================================== - PASS ./Hello.spec.ts - Hello Class - √ should create a new Hello - - Test Suites: 1 passed, 1 total - Tests: 1 passed, 1 total - Snapshots: 0 total - Time: XXs - Ran all test suites. - ================================================================================ -`; - -exports[`Simple test should pass using template "with-babel-6" 1`] = ` - √ jest - ↳ exit code: 0 - ===[ STDOUT ]=================================================================== - - ===[ STDERR ]=================================================================== - PASS ./Hello.spec.ts - Hello Class - √ should create a new Hello - - Test Suites: 1 passed, 1 total - Tests: 1 passed, 1 total - Snapshots: 0 total - Time: XXs - Ran all test suites. - ================================================================================ -`; - -exports[`Simple test should pass using template "with-babel-7" 1`] = ` - √ jest - ↳ exit code: 0 - ===[ STDOUT ]=================================================================== - - ===[ STDERR ]=================================================================== - PASS ./Hello.spec.ts - Hello Class - √ should create a new Hello - - Test Suites: 1 passed, 1 total - Tests: 1 passed, 1 total - Snapshots: 0 total - Time: XXs - Ran all test suites. - ================================================================================ -`; - -exports[`Simple test should pass using template "with-jest-22" 1`] = ` - √ jest - ↳ exit code: 0 - ===[ STDOUT ]=================================================================== - - ===[ STDERR ]=================================================================== - PASS ./Hello.spec.ts - Hello Class - √ should create a new Hello - - Test Suites: 1 passed, 1 total - Tests: 1 passed, 1 total - Snapshots: 0 total - Time: XXs - Ran all test suites. - ================================================================================ -`; - -exports[`Simple test should pass using template "with-typescript-2-7" 1`] = ` - √ jest - ↳ exit code: 0 - ===[ STDOUT ]=================================================================== - - ===[ STDERR ]=================================================================== - PASS ./Hello.spec.ts - Hello Class - √ should create a new Hello - - Test Suites: 1 passed, 1 total - Tests: 1 passed, 1 total - Snapshots: 0 total - Time: XXs - Ran all test suites. - ================================================================================ -`; diff --git a/e2e/__tests__/__snapshots__/source-map.test.ts.snap b/e2e/__tests__/__snapshots__/source-map.test.ts.snap index d599ee72ce..4f10c0e99d 100644 --- a/e2e/__tests__/__snapshots__/source-map.test.ts.snap +++ b/e2e/__tests__/__snapshots__/source-map.test.ts.snap @@ -34,7 +34,7 @@ exports[`using template "default" should have the source maps comment 1`] = ` `; exports[`using template "default" should report correct line numbers 1`] = ` - × jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"diagnostics":{"ignoreCodes":[5023,7027]}}}} + × jest --no-cache ↳ exit code: 1 ===[ STDOUT ]=================================================================== console.log main.ts:2 @@ -121,7 +121,7 @@ exports[`using template "with-babel-6" should have the source maps comment 1`] = `; exports[`using template "with-babel-6" should report correct line numbers 1`] = ` - × jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"babelConfig":true,"diagnostics":{"ignoreCodes":[5023,7027]}}}} + × jest --no-cache ↳ exit code: 1 ===[ STDOUT ]=================================================================== console.log main.ts:2 @@ -214,7 +214,7 @@ exports[`using template "with-babel-7" should have the source maps comment 1`] = `; exports[`using template "with-babel-7" should report correct line numbers 1`] = ` - × jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"babelConfig":true,"diagnostics":{"ignoreCodes":[5023,7027]}}}} + × jest --no-cache ↳ exit code: 1 ===[ STDOUT ]=================================================================== console.log main.ts:2 @@ -301,7 +301,7 @@ exports[`using template "with-jest-22" should have the source maps comment 1`] = `; exports[`using template "with-jest-22" should report correct line numbers 1`] = ` - × jest --config {"transform":{"^.+\\\\.tsx?$":"ts-jest"},"testMatch":["**/__tests__/**/*.js?(x)","**/?(*.)+(spec|test).js?(x)","**/__tests__/**/*.ts?(x)","**/?(*.)+(spec|test).ts?(x)"],"moduleFileExtensions":["js","json","jsx","node","ts","tsx"],"testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"diagnostics":{"ignoreCodes":[5023,7027]}}}} + × jest --no-cache ↳ exit code: 1 ===[ STDOUT ]=================================================================== console.log main.ts:2 @@ -386,7 +386,7 @@ exports[`using template "with-typescript-2-7" should have the source maps commen `; exports[`using template "with-typescript-2-7" should report correct line numbers 1`] = ` - × jest --config {"preset":"ts-jest","testEnvironment":"node","globals":{"ts-jest":{"tsConfig":{},"diagnostics":{"ignoreCodes":[5023,7027]}}}} + × jest --no-cache ↳ exit code: 1 ===[ STDOUT ]=================================================================== console.log main.ts:2 diff --git a/e2e/__tests__/diagnostics.test.ts b/e2e/__tests__/diagnostics.test.ts index a477d929d7..a118b33e6a 100644 --- a/e2e/__tests__/diagnostics.test.ts +++ b/e2e/__tests__/diagnostics.test.ts @@ -14,7 +14,10 @@ describe('With diagnostics, first throws', () => { }) describe('With diagnostics, warn only', () => { - const testCase = configureTestCase('diagnostics', { tsJestConfig: { diagnostics: { warnOnly: true } } }) + const testCase = configureTestCase('diagnostics', { + tsJestConfig: { diagnostics: { warnOnly: true } }, + noCache: true, // warnings shown only on first compilation + }) testCase.runWithTemplates(allValidPackageSets, 0, (runTest, { testLabel }) => { it(testLabel, () => { diff --git a/e2e/__tests__/logger.test.ts b/e2e/__tests__/logger.test.ts index a983471104..0352fa9eaf 100644 --- a/e2e/__tests__/logger.test.ts +++ b/e2e/__tests__/logger.test.ts @@ -19,15 +19,16 @@ describe('With unsupported version test', () => { describe('TS_JEST_LOG', () => { const testCase = configureTestCase('simple', { env: { TS_JEST_LOG: 'ts-jest.log' }, + noCache: true, }) testCase.runWithTemplates(allValidPackageSets, 0, (runTest, { templateName }) => { - it(`should pass and create log file when using tempalte "${templateName}"`, () => { + it(`should pass and create log file when using template "${templateName}"`, () => { const result = runTest() expect(result.status).toBe(0) expect(existsSync(result.logFilePath)) const filteredEntries = result.logFileEntries - // keep only debu and above + // keep only debug and above .filter(m => (m.context[LogContexts.logLevel] || 0) >= LogLevels.debug) // simplify entires .map(e => result.normalize(`[level:${e.context[LogContexts.logLevel]}] ${e.message}`)) diff --git a/e2e/__tests__/simple.test.ts b/e2e/__tests__/ts-jest-checks.test.ts similarity index 72% rename from e2e/__tests__/simple.test.ts rename to e2e/__tests__/ts-jest-checks.test.ts index c416c4cdb7..99a0554378 100644 --- a/e2e/__tests__/simple.test.ts +++ b/e2e/__tests__/ts-jest-checks.test.ts @@ -1,14 +1,13 @@ import { allValidPackageSets } from '../__helpers__/templates' import { configureTestCase } from '../__helpers__/test-case' -describe('Simple test', () => { - const testCase = configureTestCase('simple') +describe('ts-jest internal checks test', () => { + const testCase = configureTestCase('ts-jest-checks') testCase.runWithTemplates(allValidPackageSets, 0, (runTest, { testLabel }) => { it(testLabel, () => { const result = runTest() expect(result.status).toBe(0) - expect(result).toMatchSnapshot() }) }) }) diff --git a/e2e/jest.config.js b/e2e/jest.config.js index dfdb22a59c..2ce70c5dc7 100644 --- a/e2e/jest.config.js +++ b/e2e/jest.config.js @@ -11,4 +11,5 @@ module.exports = { '/e2e/__serializers__/processed-source.ts', ], verbose: true, + cacheDirectory: '/.cache/e2e', } diff --git a/jest.config.js b/jest.config.js index b11cb8a378..a056994a39 100644 --- a/jest.config.js +++ b/jest.config.js @@ -15,4 +15,5 @@ module.exports = { moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'], testEnvironment: 'node', snapshotSerializers: ['/src/__serializers__/processed-source.ts'], + cacheDirectory: '/.cache/unit', } diff --git a/package.json b/package.json index f6db519180..73b72b6848 100644 --- a/package.json +++ b/package.json @@ -4,35 +4,36 @@ "main": "dist/index.js", "types": "dist/index.d.ts", "bin": "cli.js", - "description": "A preprocessor with sourcemap support to help use Typescript with Jest", + "description": "A preprocessor with source maps support to help use TypeScript with Jest", "scripts": { "prebuild": "node scripts/clean-dist.js", "build": "tsc -p tsconfig.build.json", + "postbuild": "node scripts/post-build.js", "build:watch": "tsc -p tsconfig.build.json -w", "clean": "node scripts/clean.js", - "pretest": "run-s typecheck lint", + "pretest": "npm run lint", "test": "run-s -s test:e2e \"test:unit -- {@}\" --", "test:prepare": "npm run test:e2e -- --prepareOnly", "test:e2e": "node scripts/e2e.js", - "test:unit": "jest", + "test:unit": "node_modules/.bin/jest", "test:external": "node scripts/test-external-project.js", "lint": "run-s lint:ts lint:js", - "lint:js": "eslint . -f stylish", - "lint:ts": "tslint -t stylish --project .", + "lint:js": "node_modules/.bin/eslint . -f stylish", + "lint:ts": "node_modules/.bin/tslint -t stylish --project .", "lint:fix": "run-s lint:fix:ts lint:fix:js", - "lint:fix:js": "eslint . --fix", - "lint:fix:ts": "tslint --fix --project .", - "typecheck": "tsc -p . --noEmit", + "lint:fix:js": "node_modules/.bin/eslint . --fix", + "lint:fix:ts": "node_modules/.bin/tslint --fix --project .", + "typecheck": "node_modules/.bin/tsc -p .", "doc": "cd docs && bundle exec jekyll serve --livereload", "doc:link": "git worktree add docs/_site gh-pages", "doc:unlink": "git worktree prune", "doc:build": "cd docs && bundle exec jekyll build", "doc:build-commit": "npm run doc:build && cd docs/_site && git add --all && git commit -m \"Updates github pages\"", + "changelog": "node_modules/.bin/conventional-changelog -p angular -i CHANGELOG.md -s -r 0", "prepare": "npm run build", "prepublishOnly": "npm run test", - "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s -r 0", - "commitmsg": "commitlint -E GIT_PARAMS", - "precommit": "lint-staged", + "commitmsg": "node_modules/.bin/commitlint -E GIT_PARAMS", + "precommit": "node_modules/.bin/lint-staged", "postcommit": "git reset", "preversion": "npm run test", "version": "npm run changelog && git add CHANGELOG.md" diff --git a/scripts/e2e.js b/scripts/e2e.js index 3d988bf653..dcc9fcb2ac 100755 --- a/scripts/e2e.js +++ b/scripts/e2e.js @@ -8,7 +8,7 @@ const path = require('path') const Paths = require('./lib/paths') const { createHash } = require('crypto') const logger = require('./lib/logger') -const { createBundle, packageDigest } = require('./lib/bundle') +const { createBundle, readPackageDigest } = require('./lib/bundle') const npm = require('./lib/npm') const configFile = path.join(Paths.e2eRootDir, 'jest.config.js') @@ -49,8 +49,7 @@ function setupE2e() { ) // get the hash of the bundle (to know if we should install it again or not) - // we need to compute it ourselfs as the npm pack creates different tgz even tho content has not changed - const bundleHash = packageDigest(bundle) + const bundleHash = readPackageDigest() log('ts-jest digest:', bundleHash) // ensure directory exists before copying over @@ -166,8 +165,8 @@ setupE2e() log('templates are ready') if (!prepareOnly) { - log('clearing Jest cache') - spawnSync('jest', ['--clearCache']) + // log('clearing Jest cache') + // spawnSync('jest', ['--clearCache']) log('running tests') jest.run(['--config', configFile, ...parentArgs]) diff --git a/scripts/lib/bundle.js b/scripts/lib/bundle.js index a70b2e08b7..2c32874c38 100644 --- a/scripts/lib/bundle.js +++ b/scripts/lib/bundle.js @@ -1,8 +1,8 @@ const npm = require('./npm') const logger = require('./logger') -const { rootDir } = require('./paths') +const { rootDir, pkgDigestFile } = require('./paths') const { join, resolve } = require('path') -const { readFileSync, statSync } = require('fs') +const { readFileSync, statSync, writeFileSync, existsSync } = require('fs-extra') const { createHash } = require('crypto') const { sync: globIgnore } = require('glob-gitignore') @@ -19,7 +19,11 @@ function createBundle(log = logger.log.bind(logger)) { return join(rootDir, res.stdout.toString().trim()) } -function packageDigest() { +function readPackageDigest() { + return existsSync(pkgDigestFile) ? readFileSync(pkgDigestFile, 'utf8') : undefined +} + +function computePackageDigest(noWriteFile = false) { const files = globIgnore(join(rootDir, '**'), { ignore: readFileSync(join(rootDir, '.npmignore')) .toString('utf8') @@ -28,14 +32,19 @@ function packageDigest() { }) const hash = createHash('sha1') files.sort().forEach(file => { - if (statSync(file).isDirectory()) return + if (file === pkgDigestFile || statSync(file).isDirectory()) return hash.update(readFileSync(resolve(file))) hash.update('\x00') }) - return hash.digest('hex') + const digest = hash.digest('hex') + if (!noWriteFile) { + writeFileSync(pkgDigestFile, digest, 'utf8') + } + return digest } module.exports = { createBundle, - packageDigest, + computePackageDigest, + readPackageDigest, } diff --git a/scripts/lib/paths.d.ts b/scripts/lib/paths.d.ts index 6a346dcd24..15e6af7057 100644 --- a/scripts/lib/paths.d.ts +++ b/scripts/lib/paths.d.ts @@ -1,4 +1,6 @@ declare const rootDir: string +declare const cacheDir: string +declare const pkgDigestFile: string declare const e2eSourceDir: string declare const e2eRootDir: string declare const e2eWorkDir: string @@ -11,6 +13,8 @@ declare const e2eTestsDir: string export { rootDir, + cacheDir, + pkgDigestFile, e2eSourceDir, e2eRootDir, e2eWorkDir, diff --git a/scripts/lib/paths.js b/scripts/lib/paths.js index 8abc889a5a..1b7db61525 100644 --- a/scripts/lib/paths.js +++ b/scripts/lib/paths.js @@ -2,6 +2,8 @@ const path = require('path') const os = require('os') const rootDir = path.resolve(__dirname, '..', '..') +const cacheDir = path.join(rootDir, '.cache') +const pkgDigestFile = path.join(rootDir, '.ts-jest-digest') const distDir = path.join(rootDir, 'dist') const testsRootDir = path.join(rootDir, 'tests') const e2eRootDir = path.join(rootDir, 'e2e') @@ -15,6 +17,8 @@ const e2eWorkTemplatesDir = path.join(e2eWorkDir, '__templates__') const e2eWotkDirLink = path.join(e2eRootDir, '__workdir_synlink__') module.exports = { + pkgDigestFile, + cacheDir, rootDir, e2eSourceDir, e2eRootDir, diff --git a/scripts/post-build.js b/scripts/post-build.js new file mode 100644 index 0000000000..c88e7b5796 --- /dev/null +++ b/scripts/post-build.js @@ -0,0 +1,3 @@ +const { computePackageDigest } = require('./lib/bundle') + +computePackageDigest() diff --git a/src/__mocks__/index.ts b/src/__mocks__/index.ts new file mode 100644 index 0000000000..54c4bda3d1 --- /dev/null +++ b/src/__mocks__/index.ts @@ -0,0 +1,6 @@ +export const version = '1.2.3-test.0' +export const digest = 'a0d51ca854194df8191d0e65c0ca4730f510f332' +export const createTransformer = jest.fn() +export const jestPreset = { jestPreset: true } +export const createJestPreset = jest.fn() +export const pathsToModuleNameMapper = jest.fn() diff --git a/src/compiler.spec.ts b/src/compiler.spec.ts index 6603bcb703..ad984def7a 100644 --- a/src/compiler.spec.ts +++ b/src/compiler.spec.ts @@ -1,5 +1,6 @@ // tslint:disable:max-line-length import { LogLevels } from 'bs-logger' +import { removeSync, writeFileSync } from 'fs-extra' import * as fakers from './__helpers__/fakers' import { logTargetMock } from './__helpers__/mocks' @@ -34,8 +35,8 @@ beforeEach(() => { logTarget.clear() }) -describe('isolatedModules', () => { - const compiler = makeCompiler() +describe('typings', () => { + const compiler = makeCompiler({ tsJestConfig: { tsConfig: false } }) it('should report diagnostics related to typings', () => { expect(() => compiler.compile( @@ -55,7 +56,7 @@ foo.ts(4,7): error TS2322: Type 'string' is not assignable to type 'boolean'." }) describe('source-maps', () => { - const compiler = makeCompiler() + const compiler = makeCompiler({ tsJestConfig: { tsConfig: false } }) it('should have correct source maps', () => { const source = 'const f = (v: number) => v\nconst t: number = f(5)' const compiled = compiler.compile(source, __filename) @@ -74,6 +75,7 @@ describe('cache', () => { const tmp = tempDir('compiler') const compiler = makeCompiler({ jestConfig: { cache: true, cacheDirectory: tmp }, + tsJestConfig: { tsConfig: false }, }) const source = 'console.log("hello")' @@ -107,12 +109,11 @@ Array [ expect(new ProcessedSource(compiled1, __filename)).toMatchInlineSnapshot(` ===[ FILE: src/compiler.spec.ts ]=============================================== - "use strict"; console.log("hello"); - //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJmaWxlIjoiPGN3ZD4vc3JjL2NvbXBpbGVyLnNwZWMudHMiLCJtYXBwaW5ncyI6IjtBQUFBLE9BQU8sQ0FBQyxHQUFHLENBQUMsT0FBTyxDQUFDLENBQUEiLCJuYW1lcyI6W10sInNvdXJjZXMiOlsiPGN3ZD4vc3JjL2NvbXBpbGVyLnNwZWMudHMiXSwic291cmNlc0NvbnRlbnQiOlsiY29uc29sZS5sb2coXCJoZWxsb1wiKSJdLCJ2ZXJzaW9uIjozfQ== + //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJmaWxlIjoiPGN3ZD4vc3JjL2NvbXBpbGVyLnNwZWMudHMiLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxDQUFDLEdBQUcsQ0FBQyxPQUFPLENBQUMsQ0FBQSIsIm5hbWVzIjpbXSwic291cmNlcyI6WyI8Y3dkPi9zcmMvY29tcGlsZXIuc3BlYy50cyJdLCJzb3VyY2VzQ29udGVudCI6WyJjb25zb2xlLmxvZyhcImhlbGxvXCIpIl0sInZlcnNpb24iOjN9 ===[ INLINE SOURCE MAPS ]======================================================= file: /src/compiler.spec.ts - mappings: ';AAAA,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA' + mappings: 'AAAA,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA' names: [] sources: - /src/compiler.spec.ts @@ -154,8 +155,39 @@ describe('isolatedModules', () => { }) }) +describe('allowJs', () => { + const compiler = makeCompiler({ tsJestConfig: { tsConfig: { allowJs: true } } }) + const fileName = `${__filename}.test.js` + afterAll(() => { + removeSync(fileName) + }) + it('should compile js file', () => { + const source = 'export default 42' + writeFileSync(fileName, source, 'utf8') + const compiled = compiler.compile(source, fileName) + const processed = new ProcessedSource(compiled, fileName) + expect(processed).toMatchInlineSnapshot(` + ===[ FILE: src/compiler.spec.ts.test.js ]======================================= + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = 42; + //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJmaWxlIjoiPGN3ZD4vc3JjL2NvbXBpbGVyLnNwZWMudHMudGVzdC5qcyIsIm1hcHBpbmdzIjoiOztBQUFBLGtCQUFlLEVBQUUsQ0FBQSIsIm5hbWVzIjpbXSwic291cmNlcyI6WyI8Y3dkPi9zcmMvY29tcGlsZXIuc3BlYy50cy50ZXN0LmpzIl0sInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBkZWZhdWx0IDQyIl0sInZlcnNpb24iOjN9 + ===[ INLINE SOURCE MAPS ]======================================================= + file: /src/compiler.spec.ts.test.js + mappings: ';;AAAA,kBAAe,EAAE,CAAA' + names: [] + sources: + - /src/compiler.spec.ts.test.js + sourcesContent: + - export default 42 + version: 3 + ================================================================================ +`) + }) +}) + describe('getTypeInfo', () => { - const compiler = makeCompiler() + const compiler = makeCompiler({ tsJestConfig: { tsConfig: false } }) const source = ` type MyType { /** the prop 1! */ diff --git a/src/compiler.ts b/src/compiler.ts index 770aa583bd..d910f99b57 100644 --- a/src/compiler.ts +++ b/src/compiler.ts @@ -191,11 +191,13 @@ export function createCompiler(configs: ConfigSet): TsCompiler { configs.raiseDiagnostics(diagnostics, fileName, logger) } + /* istanbul ignore next (this should never happen but is kept for security) */ if (output.emitSkipped) { throw new TypeError(`${relative(cwd, fileName)}: Emit skipped`) } // Throw an error when requiring `.d.ts` files. + /* istanbul ignore next (this should never happen but is kept for security) */ if (output.outputFiles.length === 0) { throw new TypeError( interpolate(Errors.UnableToRequireDefinitionFile, { diff --git a/src/config/config-set.spec.ts b/src/config/config-set.spec.ts index e5a7bc3988..a357fc9bbe 100644 --- a/src/config/config-set.spec.ts +++ b/src/config/config-set.spec.ts @@ -2,7 +2,7 @@ import { testing } from 'bs-logger' import { resolve } from 'path' import ts, { Diagnostic, ModuleKind, ScriptTarget } from 'typescript' -import { version as currentVersion } from '../../package.json' +import * as _myModule from '..' import * as fakers from '../__helpers__/fakers' import { logTargetMock, mocked } from '../__helpers__/mocks' import { TsJestGlobalOptions } from '../types' @@ -12,8 +12,10 @@ import { normalizeSlashes } from '../util/normalize-slashes' import { ConfigSet, IGNORE_DIAGNOSTIC_CODES, MATCH_NOTHING } from './config-set' jest.mock('../util/backports') +jest.mock('../index') const backports = mocked(_backports) +const myModule = mocked(_myModule) backports.backportJestConfig.mockImplementation((_, config) => ({ ...config, @@ -385,7 +387,7 @@ describe('versions', () => { it('should return correct version map', () => { expect(createConfigSet().versions).toEqual({ jest: pkgVersion('jest'), - 'ts-jest': currentVersion, + 'ts-jest': myModule.version, typescript: pkgVersion('typescript'), }) }) @@ -397,13 +399,19 @@ describe('versions', () => { 'babel-core': pkgVersion('babel-core'), 'babel-jest': pkgVersion('babel-jest'), jest: pkgVersion('jest'), - 'ts-jest': currentVersion, + 'ts-jest': myModule.version, typescript: pkgVersion('typescript'), }) }) }) }) // versions +describe('tsJestDigest', () => { + it('should be the package digest', () => { + expect(createConfigSet().tsJestDigest).toBe(myModule.digest) + }) +}) // tsJestDigest + describe('tsconfig', () => { it('should return input tsconfig', () => { const cs = createConfigSet({ tsJestConfig: { tsConfig: { target: 'ES6' } } as any }) @@ -468,8 +476,9 @@ describe('cacheKey', () => { const val = cs.jsonValue.value delete val.versions cs.jsonValue.value = val + // digest is mocked in src/__mocks__/index.ts expect(cs.cacheKey).toMatchInlineSnapshot( - `"{\\"jest\\":{\\"__backported\\":true,\\"globals\\":{}},\\"transformers\\":[\\"hoisting-jest-mock@1\\"],\\"tsJest\\":{\\"compiler\\":\\"typescript\\",\\"diagnostics\\":{\\"ignoreCodes\\":[6059,18002,18003],\\"pretty\\":true,\\"throws\\":true},\\"isolatedModules\\":false,\\"transformers\\":[]},\\"tsconfig\\":{\\"compilerOptions\\":{}}}"`, + `"{\\"digest\\":\\"a0d51ca854194df8191d0e65c0ca4730f510f332\\",\\"jest\\":{\\"__backported\\":true,\\"globals\\":{}},\\"transformers\\":[\\"hoisting-jest-mock@1\\"],\\"tsJest\\":{\\"compiler\\":\\"typescript\\",\\"diagnostics\\":{\\"ignoreCodes\\":[6059,18002,18003],\\"pretty\\":true,\\"throws\\":true},\\"isolatedModules\\":false,\\"transformers\\":[]},\\"tsconfig\\":{\\"declaration\\":false,\\"inlineSourceMap\\":false,\\"inlineSources\\":true,\\"module\\":1,\\"noEmit\\":false,\\"outDir\\":\\"$$ts-jest$$\\",\\"removeComments\\":false,\\"sourceMap\\":true,\\"target\\":1}}"`, ) }) }) // cacheKey @@ -479,13 +488,15 @@ describe('jsonValue', () => { const cs = createConfigSet({ tsJestConfig: { tsConfig: false } as any }) const val = cs.jsonValue.valueOf() expect(cs.toJSON()).toEqual(val) - // it will change each time we upgrade and we tested those in the `version` block + // it will change each time we upgrade – we tested those in the `version` block expect(val.versions).toEqual(cs.versions) delete val.versions + // digest is mocked in src/__mocks__/index.ts expect(val).toMatchInlineSnapshot(` Object { "babel": undefined, + "digest": "a0d51ca854194df8191d0e65c0ca4730f510f332", "jest": Object { "__backported": true, "globals": Object {}, @@ -511,7 +522,16 @@ Object { "tsConfig": undefined, }, "tsconfig": Object { - "compilerOptions": Object {}, + "configFilePath": undefined, + "declaration": false, + "inlineSourceMap": false, + "inlineSources": true, + "module": 1, + "noEmit": false, + "outDir": "$$ts-jest$$", + "removeComments": false, + "sourceMap": true, + "target": 1, }, } `) diff --git a/src/config/config-set.ts b/src/config/config-set.ts index 00acbfafc9..4d1c1debfd 100644 --- a/src/config/config-set.ts +++ b/src/config/config-set.ts @@ -23,7 +23,7 @@ import { SourceFile, } from 'typescript' -import { version as myVersion } from '..' +import { digest as MY_DIGEST, version as MY_VERSION } from '..' import { createCompiler } from '../compiler' import { internals as internalAstTransformers } from '../transformers' import { @@ -229,7 +229,7 @@ export class ConfigSet { map[name] = getPackageVersion(name) || '-' return map }, - { 'ts-jest': myVersion } as Record, + { 'ts-jest': MY_VERSION } as Record, ) } @@ -438,10 +438,10 @@ export class ConfigSet { compiler: this.tsJest.compiler, compilerOptions: this.typescript.options, isolatedModules: this.tsJest.isolatedModules, - ignoreDiagnostics: this.tsJest.diagnostics.ignoreCodes, + diagnostics: this.tsJest.diagnostics, }), ) - const res = join(this.jest.cacheDirectory, `ts-jest-${cacheSuffix}`) + const res = join(this.jest.cacheDirectory, 'ts-jest', cacheSuffix.substr(0, 2), cacheSuffix.substr(2)) logger.debug({ cacheDirectory: res }, `will use file caching`) return res } @@ -489,6 +489,11 @@ export class ConfigSet { return !!process.env.TS_JEST_DOCTOR } + @Memoize() + get tsJestDigest(): string { + return MY_DIGEST + } + /** * @internal */ @@ -505,11 +510,12 @@ export class ConfigSet { return new JsonableValue({ versions: this.versions, + digest: this.tsJestDigest, transformers: this.astTransformers.map(t => `${t.name}@${t.version}`), jest, tsJest: this.tsJest, babel: this.babel, - tsconfig: this.tsconfig, + tsconfig: this.typescript.options, }) } diff --git a/src/index.ts b/src/index.ts index 76e8775a37..15806be569 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,6 @@ +import { readFileSync } from 'fs' +import { resolve } from 'path' + import { createJestPreset } from './config/create-jest-preset' import { pathsToModuleNameMapper } from './config/paths-to-module-name-mapper' import { TsJestTransformer } from './ts-jest-transformer' @@ -6,6 +9,7 @@ import { VersionCheckers } from './util/version-checkers' // tslint:disable-next-line:no-var-requires export const version: string = require('../package.json').version +export const digest: string = readFileSync(resolve(__dirname, '..', '.ts-jest-digest'), 'utf8') let transformer!: TsJestTransformer function defaultTransformer(): TsJestTransformer {