Skip to content

Commit 5bbfd06

Browse files
authoredNov 11, 2020
refactor: move jest transformer class to package entry (#2122)
BREAKING CHANGE: - One currently refers type in `jest.config.js` ``` /** @typedef {import('ts-jest')} */ module.exports = { //... } ``` should change to ``` /** @typedef {import('ts-jest/dist/types')} */ module.exports = { //... } ``` - Remove possibilities to import `mocked`, `createJestPreset`, `pathsToModuleNameMapper` from package entry. One should change to ``` import { mocked, createJestPreset, pathsToModuleNameMapper` } from 'ts-jest/utils' ```
1 parent 3cc9b80 commit 5bbfd06

File tree

11 files changed

+371
-521
lines changed

11 files changed

+371
-521
lines changed
 

‎docs/user/config/index.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ module.exports = {
186186
To utilize IDE suggestions, you can use `JSDoc` comments to provide suggested `ts-jest` configs for your Jest config:
187187

188188
```js
189-
/** @typedef {import('ts-jest')} */
189+
/** @typedef {import('ts-jest/dist/types')} */
190190
/** @type {import('@jest/types').Config.InitialOptions} */
191191
const config = {
192192
// [...]

‎e2e/__cases__/test-helpers/deprecated.spec.ts

-9
This file was deleted.

‎e2e/__tests__/__snapshots__/logger.test.ts.snap

-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ Array [
55
"[level:20] creating jest presets not handling JavaScript files",
66
"[level:20] creating jest presets not handling JavaScript files",
77
"[level:20] creating Importer singleton",
8-
"[level:20] checking version of jest: OK",
98
"[level:20] created new transformer",
109
"[level:30] no matching config-set found, creating a new one",
1110
"[level:20] loaded module typescript",
@@ -44,7 +43,6 @@ Array [
4443
"[level:20] creating jest presets not handling JavaScript files",
4544
"[level:20] creating jest presets not handling JavaScript files",
4645
"[level:20] creating Importer singleton",
47-
"[level:20] checking version of jest: OK",
4846
"[level:20] created new transformer",
4947
"[level:30] no matching config-set found, creating a new one",
5048
"[level:20] loaded module typescript",
@@ -89,7 +87,6 @@ Array [
8987
"[level:20] creating jest presets not handling JavaScript files",
9088
"[level:20] creating jest presets not handling JavaScript files",
9189
"[level:20] creating Importer singleton",
92-
"[level:20] checking version of jest: OK",
9390
"[level:20] created new transformer",
9491
"[level:30] no matching config-set found, creating a new one",
9592
"[level:20] loaded module typescript",

‎e2e/__tests__/__snapshots__/test-helpers.test.ts.snap

+4-10
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,8 @@ exports[`test-helpers 1`] = `
1919
9 expect(mocked(bar, true).dummy.deep.deeper(42)).toBeUndefined()
2020
~~
2121
22-
ts-jest[root] (WARN) The \`mocked\` helper has been moved to \`ts-jest/utils\`. Use \`import { mocked } from 'ts-jest/utils'\` instead.
23-
PASS ./deprecated.spec.ts
24-
25-
Test Suites: 1 failed, 2 passed, 3 total
26-
Tests: 4 passed, 4 total
22+
Test Suites: 1 failed, 1 passed, 2 total
23+
Tests: 3 passed, 3 total
2724
Snapshots: 0 total
2825
Time: XXs
2926
Ran all test suites.
@@ -49,11 +46,8 @@ exports[`with esModuleInterop set to false 1`] = `
4946
9 expect(mocked(bar, true).dummy.deep.deeper(42)).toBeUndefined()
5047
~~
5148
52-
ts-jest[root] (WARN) The \`mocked\` helper has been moved to \`ts-jest/utils\`. Use \`import { mocked } from 'ts-jest/utils'\` instead.
53-
PASS ./deprecated.spec.ts
54-
55-
Test Suites: 1 failed, 2 passed, 3 total
56-
Tests: 4 passed, 4 total
49+
Test Suites: 1 failed, 1 passed, 2 total
50+
Tests: 3 passed, 3 total
5751
Snapshots: 0 total
5852
Time: XXs
5953
Ran all test suites.

‎src/index.spec.ts

+174-84
Original file line numberDiff line numberDiff line change
@@ -1,104 +1,194 @@
1-
import type { testing } from 'bs-logger'
1+
import { LogLevels } from 'bs-logger'
2+
import { sep } from 'path'
23

3-
import * as tsJest from '.'
4+
import { ConfigSet } from './config/config-set'
5+
import { SOURCE_MAPPING_PREFIX } from './compiler/instance'
46
import { logTargetMock } from './__helpers__/mocks'
5-
import { TsJestTransformer } from './ts-jest-transformer'
67

7-
jest.mock('./ts-jest-transformer', () => {
8-
class TsJestTransformer {
9-
process: jest.Mock = jest.fn()
10-
getCacheKey: jest.Mock = jest.fn()
11-
constructor(public opt?: any) {}
12-
}
8+
const logTarget = logTargetMock()
139

14-
return { TsJestTransformer }
10+
beforeEach(() => {
11+
logTarget.clear()
1512
})
16-
jest.mock('./presets/create-jest-preset', () => ({
17-
createJestPreset: () => ({ jestPreset: true }),
18-
}))
1913

20-
describe('ts-jest', () => {
21-
it('should export a `createTransformer` function', () => {
22-
expect(typeof tsJest.createTransformer).toBe('function')
23-
})
14+
describe('TsJestTransformer', () => {
15+
describe('configFor', () => {
16+
test('should return the same config-set for same values with jest config string is not in configSetsIndex', () => {
17+
const obj1 = { cwd: '/foo/.', rootDir: '/bar//dummy/..', globals: {} }
18+
const cs3 = require('./').configsFor(obj1 as any)
2419

25-
it('should export a `createJestPreset` function', () => {
26-
expect(typeof tsJest.createJestPreset).toBe('function')
27-
})
20+
expect(cs3.cwd).toBe(`${sep}foo`)
21+
expect(cs3.rootDir).toBe(`${sep}bar`)
22+
})
2823

29-
it('should export a `mocked` function', () => {
30-
expect(typeof tsJest.mocked).toBe('function')
31-
})
24+
test('should return the same config-set for same values with jest config string in configSetsIndex', () => {
25+
const obj1 = { cwd: '/foo/.', rootDir: '/bar//dummy/..', globals: {} }
26+
const obj2 = { ...obj1 }
27+
const cs1 = require('./').configsFor(obj1 as any)
28+
const cs2 = require('./').configsFor(obj2 as any)
3229

33-
it('should export a `pathsToModuleNameMapper` function', () => {
34-
expect(typeof tsJest.pathsToModuleNameMapper).toBe('function')
30+
expect(cs1.cwd).toBe(`${sep}foo`)
31+
expect(cs1.rootDir).toBe(`${sep}bar`)
32+
expect(cs2).toBe(cs1)
33+
})
3534
})
36-
})
3735

38-
describe('old entry point', () => {
39-
const MANIFEST = { tsJestIndex: true }
40-
const spy = jest.spyOn(console, 'warn')
41-
spy.mockImplementation(() => undefined)
42-
afterAll(() => {
43-
spy.mockRestore()
44-
})
36+
describe('getCacheKey', () => {
37+
test('should be different for each argument value', () => {
38+
const tr = require('./')
39+
const input = {
40+
fileContent: 'export default "foo"',
41+
fileName: 'foo.ts',
42+
jestConfigStr: '{"foo": "bar"}',
43+
options: { config: { foo: 'bar' } as any, instrument: false, rootDir: '/foo' },
44+
}
45+
const keys = [
46+
tr.getCacheKey(input.fileContent, input.fileName, input.jestConfigStr, input.options),
47+
tr.getCacheKey(input.fileContent, 'bar.ts', input.jestConfigStr, input.options),
48+
tr.getCacheKey(input.fileContent, input.fileName, '{}', { ...input.options, instrument: true }),
49+
tr.getCacheKey(input.fileContent, input.fileName, '{}', { ...input.options, rootDir: '/bar' }),
50+
]
4551

46-
it('should warn when using old path to ts-jest', () => {
47-
jest.mock('../dist/index', () => MANIFEST)
48-
expect(require('../preprocessor.js')).toBe(MANIFEST)
49-
expect(spy).toHaveBeenCalledTimes(1)
50-
expect(spy.mock.calls[0]).toMatchInlineSnapshot(`
51-
Array [
52-
"ts-jest[main] (WARN) Replace any occurrences of \\"ts-jest/dist/preprocessor.js\\" or \\"<rootDir>/node_modules/ts-jest/preprocessor.js\\" in the 'transform' section of your Jest config with just \\"ts-jest\\".",
53-
]
54-
`)
52+
// each key should have correct length
53+
for (const key of keys) {
54+
expect(key).toHaveLength(40)
55+
}
56+
// unique array should have same length
57+
expect(keys.filter((k, i, all) => all.indexOf(k) === i)).toHaveLength(keys.length)
58+
})
5559
})
56-
})
5760

58-
describe('moved helpers', () => {
59-
let target: testing.LogTargetMock
60-
beforeEach(() => {
61-
target = logTargetMock()
62-
target.clear()
63-
})
61+
describe('process', () => {
62+
let tr!: any
6463

65-
it('should warn when using mocked', () => {
66-
tsJest.mocked(42)
67-
expect(target.lines.warn).toMatchInlineSnapshot(`
68-
Array [
69-
"[level:40] The \`mocked\` helper has been moved to \`ts-jest/utils\`. Use \`import { mocked } from 'ts-jest/utils'\` instead.
70-
",
71-
]
72-
`)
73-
})
64+
beforeEach(() => {
65+
tr = require('./')
66+
})
7467

75-
it('should warn when using createJestPreset', () => {
76-
tsJest.createJestPreset()
77-
expect(target.lines.warn).toMatchInlineSnapshot(`
78-
Array [
79-
"[level:40] The \`createJestPreset\` helper has been moved to \`ts-jest/utils\`. Use \`import { createJestPreset } from 'ts-jest/utils'\` instead.
80-
",
81-
]
82-
`)
83-
})
68+
test('should process input as stringified content with content matching stringifyContentPathRegex option', () => {
69+
const fileContent = '<h1>Hello World</h1>'
70+
const filePath = 'foo.html'
71+
const jestCfg = {
72+
globals: {
73+
'ts-jest': {
74+
stringifyContentPathRegex: '\\.html$',
75+
},
76+
},
77+
} as any
78+
tr.getCacheKey(fileContent, filePath, JSON.stringify(jestCfg), { config: jestCfg } as any)
8479

85-
it('should warn when using pathsToModuleNameMapper', () => {
86-
tsJest.pathsToModuleNameMapper({})
87-
expect(target.lines.warn).toMatchInlineSnapshot(`
88-
Array [
89-
"[level:40] The \`pathsToModuleNameMapper\` helper has been moved to \`ts-jest/utils\`. Use \`import { pathsToModuleNameMapper } from 'ts-jest/utils'\` instead.
90-
",
91-
]
92-
`)
93-
})
94-
})
80+
const result = tr.process(fileContent, filePath, jestCfg)
81+
82+
expect(result).toMatchInlineSnapshot(`"module.exports=\\"<h1>Hello World</h1>\\""`)
83+
})
84+
85+
test('should process type definition input', () => {
86+
const fileContent = 'type Foo = number'
87+
const filePath = 'foo.d.ts'
88+
const jestCfg = Object.create(null)
89+
tr.getCacheKey(fileContent, filePath, JSON.stringify(jestCfg), { config: jestCfg } as any)
90+
const result = tr.process(fileContent, filePath, jestCfg)
91+
92+
expect(result).toEqual('')
93+
})
94+
95+
test('should process js file with allowJs false and show warning log', () => {
96+
const fileContent = 'const foo = 1'
97+
const filePath = 'foo.js'
98+
const jestCfg = {
99+
globals: {
100+
'ts-jest': { tsconfig: { allowJs: false } },
101+
},
102+
} as any
103+
tr.getCacheKey(fileContent, filePath, JSON.stringify(jestCfg), { config: jestCfg } as any)
104+
logTarget.clear()
105+
106+
const result = tr.process(fileContent, filePath, jestCfg)
107+
108+
expect(result).toEqual(fileContent)
109+
expect(logTarget.lines[1].substring(0)).toMatchInlineSnapshot(`
110+
"[level:40] Got a \`.js\` file to compile while \`allowJs\` option is not set to \`true\` (file: foo.js). To fix this:
111+
- if you want TypeScript to process JS files, set \`allowJs\` to \`true\` in your TypeScript config (usually tsconfig.json)
112+
- if you do not want TypeScript to process your \`.js\` files, in your Jest config change the \`transform\` key which value is \`ts-jest\` so that it does not match \`.js\` files anymore
113+
"
114+
`)
115+
})
116+
117+
test.each(['foo.ts', 'foo.tsx'])('should process ts/tsx file', (filePath) => {
118+
const fileContent = 'const foo = 1'
119+
const output = 'var foo = 1'
120+
const jestCfg = Object.create(null)
121+
tr.getCacheKey(fileContent, filePath, JSON.stringify(jestCfg), { config: jestCfg } as any)
122+
jest.spyOn(ConfigSet.prototype, 'tsCompiler', 'get').mockImplementationOnce(() => ({
123+
compile: () => output,
124+
cwd: '.',
125+
program: undefined,
126+
}))
127+
128+
const result = tr.process(fileContent, filePath, jestCfg)
129+
130+
expect(result).toEqual(output)
131+
})
132+
133+
test.each(['foo.js', 'foo.jsx'])('should process js/jsx file with allowJs true', (filePath) => {
134+
const fileContent = 'const foo = 1'
135+
const output = 'var foo = 1'
136+
const jestCfg = {
137+
globals: {
138+
'ts-jest': { tsconfig: { allowJs: true } },
139+
},
140+
} as any
141+
tr.getCacheKey(fileContent, filePath, JSON.stringify(jestCfg), { config: jestCfg } as any)
142+
logTarget.clear()
143+
jest.spyOn(ConfigSet.prototype, 'tsCompiler', 'get').mockImplementationOnce(() => ({
144+
compile: () => output,
145+
cwd: '.',
146+
program: undefined,
147+
}))
148+
149+
const result = tr.process(fileContent, filePath, jestCfg)
150+
151+
expect(result).toEqual(output)
152+
})
153+
154+
test('should process file with unknown extension and show warning message without babel-jest', () => {
155+
const fileContent = 'foo'
156+
const filePath = 'foo.bar'
157+
const jestCfg = {
158+
globals: {
159+
'ts-jest': { tsconfig: { allowJs: true } },
160+
},
161+
} as any
162+
tr.getCacheKey(fileContent, filePath, JSON.stringify(jestCfg), { config: jestCfg } as any)
163+
logTarget.clear()
164+
165+
const result = tr.process(fileContent, filePath, jestCfg)
166+
167+
expect(result).toEqual(fileContent)
168+
expect(logTarget.lines[1]).toMatchInlineSnapshot(`
169+
"[level:40] Got a unknown file type to compile (file: foo.bar). To fix this, in your Jest config change the \`transform\` key which value is \`ts-jest\` so that it does not match this kind of files anymore.
170+
"
171+
`)
172+
})
173+
174+
test.each(['foo.bar', 'foo.js'])('should process file with babel-jest', (filePath) => {
175+
const fileContent = 'foo'
176+
const jestCfg = {
177+
globals: {
178+
'ts-jest': { babelConfig: true },
179+
},
180+
} as any
181+
tr.getCacheKey(fileContent, filePath, JSON.stringify(jestCfg), { config: jestCfg } as any)
182+
logTarget.clear()
183+
184+
const result = tr.process('foo', filePath, jestCfg)
95185

96-
describe('createTransformer', () => {
97-
it('should create different instances', () => {
98-
const tr1 = tsJest.createTransformer()
99-
const tr2 = tsJest.createTransformer()
100-
expect(tr1).toBeInstanceOf(TsJestTransformer)
101-
expect(tr2).toBeInstanceOf(TsJestTransformer)
102-
expect(tr1).not.toBe(tr2)
186+
if (typeof result !== 'string') {
187+
expect(result.code.substring(0, result.code.indexOf(SOURCE_MAPPING_PREFIX))).toMatchSnapshot()
188+
}
189+
if (filePath === 'foo.bar') {
190+
expect(logTarget.filteredLines(LogLevels.warn)[0]).toMatchSnapshot()
191+
}
192+
})
103193
})
104194
})

‎src/index.ts

+183-28
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,192 @@
1-
import { LogContexts, LogLevels } from 'bs-logger'
1+
import type { CacheKeyOptions, TransformedSource, Transformer, TransformOptions } from '@jest/transform'
2+
import type { Config } from '@jest/types'
3+
import type { Logger } from 'bs-logger'
24

3-
import { createJestPreset as createJestPresetCore } from './presets/create-jest-preset'
4-
import { pathsToModuleNameMapper as pathsToModuleNameMapperCore } from './config/paths-to-module-name-mapper'
5-
import { TsJestTransformer } from './ts-jest-transformer'
6-
import type { TsJestGlobalOptions } from './types'
5+
import { ConfigSet } from './config/config-set'
6+
import { DECLARATION_TYPE_EXT, JS_JSX_REGEX, TS_TSX_REGEX } from './constants'
7+
import { stringify } from './utils/json'
8+
import { JsonableValue } from './utils/jsonable-value'
79
import { rootLogger } from './utils/logger'
8-
import { Deprecations, interpolate } from './utils/messages'
9-
import { mocked as mockedCore } from './utils/testing'
10-
import { VersionCheckers } from './utils/version-checkers'
11-
12-
declare module '@jest/types' {
13-
// eslint-disable-next-line @typescript-eslint/no-namespace
14-
namespace Config {
15-
interface ConfigGlobals {
16-
'ts-jest': TsJestGlobalOptions
10+
import { Errors, interpolate } from './utils/messages'
11+
import { sha1 } from './utils/sha1'
12+
13+
interface CachedConfigSet {
14+
configSet: ConfigSet
15+
jestConfig: JsonableValue<Config.ProjectConfig>
16+
transformerCfgStr: string
17+
}
18+
19+
class TsJestTransformer implements Transformer {
20+
/**
21+
* cache ConfigSet between test runs
22+
*
23+
* @internal
24+
*/
25+
private static readonly _cachedConfigSets: CachedConfigSet[] = []
26+
protected readonly logger: Logger
27+
protected _transformCfgStr!: string
28+
29+
constructor() {
30+
this.logger = rootLogger.child({ namespace: 'ts-jest-transformer' })
31+
32+
this.logger.debug('created new transformer')
33+
}
34+
35+
/**
36+
* @public
37+
*/
38+
configsFor(jestConfig: Config.ProjectConfig): ConfigSet {
39+
const ccs: CachedConfigSet | undefined = TsJestTransformer._cachedConfigSets.find(
40+
(cs) => cs.jestConfig.value === jestConfig,
41+
)
42+
let configSet: ConfigSet
43+
if (ccs) {
44+
this._transformCfgStr = ccs.transformerCfgStr
45+
configSet = ccs.configSet
46+
} else {
47+
// try to look-it up by stringified version
48+
const serializedJestCfg = stringify(jestConfig)
49+
const serializedCcs = TsJestTransformer._cachedConfigSets.find(
50+
(cs) => cs.jestConfig.serialized === serializedJestCfg,
51+
)
52+
if (serializedCcs) {
53+
// update the object so that we can find it later
54+
// this happens because jest first calls getCacheKey with stringified version of
55+
// the config, and then it calls the transformer with the proper object
56+
serializedCcs.jestConfig.value = jestConfig
57+
this._transformCfgStr = serializedCcs.transformerCfgStr
58+
configSet = serializedCcs.configSet
59+
} else {
60+
// create the new record in the index
61+
this.logger.info('no matching config-set found, creating a new one')
62+
63+
configSet = new ConfigSet(jestConfig)
64+
const jest = { ...jestConfig }
65+
const globals = (jest.globals = { ...jest.globals } as any)
66+
// we need to remove some stuff from jest config
67+
// this which does not depend on config
68+
jest.name = undefined as any
69+
jest.cacheDirectory = undefined as any
70+
// we do not need this since its normalized version is in tsJest
71+
delete globals['ts-jest']
72+
this._transformCfgStr = new JsonableValue({
73+
digest: configSet.tsJestDigest,
74+
babel: configSet.babelConfig,
75+
...jest,
76+
tsconfig: {
77+
options: configSet.parsedTsConfig.options,
78+
raw: configSet.parsedTsConfig.raw,
79+
},
80+
}).serialized
81+
TsJestTransformer._cachedConfigSets.push({
82+
jestConfig: new JsonableValue(jestConfig),
83+
configSet,
84+
transformerCfgStr: this._transformCfgStr,
85+
})
86+
}
1787
}
88+
89+
return configSet
1890
}
19-
}
2091

21-
// deprecate helpers
22-
const warn = rootLogger.child({ [LogContexts.logLevel]: LogLevels.warn })
23-
const helperMoved = <T extends (...args: any[]) => any>(name: string, helper: T) =>
24-
warn.wrap(interpolate(Deprecations.HelperMovedToUtils, { helper: name }), helper)
92+
/**
93+
* @public
94+
*/
95+
process(
96+
input: string,
97+
filePath: Config.Path,
98+
jestConfig: Config.ProjectConfig,
99+
transformOptions?: TransformOptions,
100+
): TransformedSource | string {
101+
this.logger.debug({ fileName: filePath, transformOptions }, 'processing', filePath)
102+
103+
let result: string | TransformedSource
104+
const source: string = input
105+
const configs = this.configsFor(jestConfig)
106+
const { hooks } = configs
107+
const shouldStringifyContent = configs.shouldStringifyContent(filePath)
108+
const babelJest = shouldStringifyContent ? undefined : configs.babelJestTransformer
109+
const isDefinitionFile = filePath.endsWith(DECLARATION_TYPE_EXT)
110+
const isJsFile = JS_JSX_REGEX.test(filePath)
111+
const isTsFile = !isDefinitionFile && TS_TSX_REGEX.test(filePath)
112+
if (shouldStringifyContent) {
113+
// handles here what we should simply stringify
114+
result = `module.exports=${stringify(source)}`
115+
} else if (isDefinitionFile) {
116+
// do not try to compile declaration files
117+
result = ''
118+
} else if (!configs.parsedTsConfig.options.allowJs && isJsFile) {
119+
// we've got a '.js' but the compiler option `allowJs` is not set or set to false
120+
this.logger.warn({ fileName: filePath }, interpolate(Errors.GotJsFileButAllowJsFalse, { path: filePath }))
121+
122+
result = source
123+
} else if (isJsFile || isTsFile) {
124+
// transpile TS code (source maps are included)
125+
/* istanbul ignore if */
126+
result = configs.tsCompiler.compile(source, filePath)
127+
} else {
128+
// we should not get called for files with other extension than js[x], ts[x] and d.ts,
129+
// TypeScript will bail if we try to compile, and if it was to call babel, users can
130+
// define the transform value with `babel-jest` for this extension instead
131+
const message = babelJest ? Errors.GotUnknownFileTypeWithBabel : Errors.GotUnknownFileTypeWithoutBabel
25132

26-
/** @deprecated */
27-
export const mocked = helperMoved('mocked', mockedCore)
28-
/** @deprecated */
29-
export const createJestPreset = helperMoved('createJestPreset', createJestPresetCore)
30-
/** @deprecated */
31-
export const pathsToModuleNameMapper = helperMoved('pathsToModuleNameMapper', pathsToModuleNameMapperCore)
133+
this.logger.warn({ fileName: filePath }, interpolate(message, { path: filePath }))
32134

33-
export function createTransformer(): TsJestTransformer {
34-
VersionCheckers.jest.warn()
135+
result = source
136+
}
137+
// calling babel-jest transformer
138+
if (babelJest) {
139+
this.logger.debug({ fileName: filePath }, 'calling babel-jest processor')
140+
141+
// do not instrument here, jest will do it anyway afterwards
142+
result = babelJest.process(result, filePath, jestConfig, { ...transformOptions, instrument: false })
143+
}
144+
// allows hooks (useful for internal testing)
145+
/* istanbul ignore next (cover by e2e) */
146+
if (hooks.afterProcess) {
147+
this.logger.debug({ fileName: filePath, hookName: 'afterProcess' }, 'calling afterProcess hook')
148+
149+
const newResult = hooks.afterProcess([input, filePath, jestConfig, transformOptions], result)
150+
if (newResult !== undefined) {
151+
return newResult
152+
}
153+
}
154+
155+
return result
156+
}
157+
158+
/**
159+
* Jest uses this to cache the compiled version of a file
160+
*
161+
* @see https://github.com/facebook/jest/blob/v23.5.0/packages/jest-runtime/src/script_transformer.js#L61-L90
162+
*
163+
* @public
164+
*/
165+
getCacheKey(
166+
fileContent: string,
167+
filePath: string,
168+
_jestConfigStr: string,
169+
transformOptions: CacheKeyOptions,
170+
): string {
171+
const configs = this.configsFor(transformOptions.config)
172+
173+
this.logger.debug({ fileName: filePath, transformOptions }, 'computing cache key for', filePath)
35174

36-
return new TsJestTransformer()
175+
// we do not instrument, ensure it is false all the time
176+
const { instrument = false, rootDir = configs.rootDir } = transformOptions
177+
178+
return sha1(
179+
this._transformCfgStr,
180+
'\x00',
181+
rootDir,
182+
'\x00',
183+
`instrument:${instrument ? 'on' : 'off'}`,
184+
'\x00',
185+
fileContent,
186+
'\x00',
187+
filePath,
188+
)
189+
}
37190
}
191+
192+
export = new TsJestTransformer()

‎src/ts-jest-transformer.spec.ts

-195
This file was deleted.

‎src/ts-jest-transformer.ts

-190
This file was deleted.

‎src/types.ts

+9
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,15 @@ import type * as _ts from 'typescript'
44

55
import type { ConfigSet } from './config/config-set'
66

7+
declare module '@jest/types' {
8+
// eslint-disable-next-line @typescript-eslint/no-namespace
9+
namespace Config {
10+
interface ConfigGlobals {
11+
'ts-jest': TsJestGlobalOptions
12+
}
13+
}
14+
}
15+
716
/**
817
* @internal
918
*/

‎src/utils/messages.ts

-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ export const enum Deprecations {
3535
ConfigOption = '"[jest-config].{{oldPath}}" is deprecated, use "[jest-config].{{newPath}}" instead.',
3636
ConfigOptionWithNote = '"[jest-config].{{oldPath}}" is deprecated, use "[jest-config].{{newPath}}" instead.\n ↳ {{note}}',
3737
ConfigOptionUseBabelRcNote = 'See `babel-jest` related issue: https://github.com/facebook/jest/issues/3845',
38-
HelperMovedToUtils = "The `{{helper}}` helper has been moved to `ts-jest/utils`. Use `import { {{helper}} } from 'ts-jest/utils'` instead.",
3938
AstTransformerArrayConfig = 'The configuration for astTransformers as string[] is deprecated and will be removed in ts-jest 27. Please define your custom AST transformers in a form of an object. More information you can check online documentation https://kulshekhar.github.io/ts-jest/user/config/astTransformers',
4039
PackageJson = 'The option `packageJson` is deprecated and will be removed in ts-jest 27. This option is not used by internal `ts-jest`',
4140
}

0 commit comments

Comments
 (0)
Please sign in to comment.