Skip to content

Commit 5bbfd06

Browse files
authored
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

11 files changed

Lines changed: 371 additions & 521 deletions

File tree

docs/user/config/index.md

Lines changed: 1 addition & 1 deletion
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

Lines changed: 0 additions & 9 deletions
This file was deleted.

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

Lines changed: 0 additions & 3 deletions
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

Lines changed: 4 additions & 10 deletions
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.
File renamed without changes.

src/index.spec.ts

Lines changed: 174 additions & 84 deletions
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
})

0 commit comments

Comments
 (0)