-
Notifications
You must be signed in to change notification settings - Fork 450
/
compiler.spec.ts
246 lines (229 loc) · 7.45 KB
/
compiler.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// tslint:disable:max-line-length
import { Config } from '@jest/types'
import { LogLevels } from 'bs-logger'
import { removeSync, writeFileSync } from 'fs-extra'
import { LanguageService, ModuleKind, ScriptTarget } from 'typescript'
import * as fakers from './__helpers__/fakers'
import { logTargetMock } from './__helpers__/mocks'
import { tempDir } from './__helpers__/path'
import ProcessedSource from './__helpers__/processed-source'
import { createCompiler } from './compiler'
import { ConfigSet } from './config/config-set'
import { TsJestGlobalOptions } from './types'
const logTarget = logTargetMock()
// not really unit-testing here, but it's hard to mock all those values :-D
function makeCompiler({
jestConfig,
tsJestConfig,
parentConfig,
}: {
jestConfig?: Partial<Config.ProjectConfig>
tsJestConfig?: TsJestGlobalOptions
parentConfig?: TsJestGlobalOptions
} = {}) {
tsJestConfig = { ...tsJestConfig }
tsJestConfig.diagnostics = {
...(tsJestConfig.diagnostics as any),
pretty: false,
}
const cs = new ConfigSet(fakers.jestConfig(jestConfig, tsJestConfig), parentConfig)
return createCompiler(cs)
}
function makeFallbackCompiler({
jestConfig,
tsJestConfig,
parentConfig,
}: {
jestConfig?: Partial<Config.ProjectConfig>
tsJestConfig?: TsJestGlobalOptions
parentConfig?: TsJestGlobalOptions
} = {}) {
const compiler = makeCompiler({ jestConfig, tsJestConfig, parentConfig })
const languageService: LanguageService = compiler.ts.createLanguageService({
getScriptFileNames: jest.fn(),
getScriptVersion: jest.fn(),
getScriptSnapshot: jest.fn(),
getCurrentDirectory: () => '.',
getDefaultLibFileName: jest.fn(),
getCompilationSettings: () => {
return {
target: ScriptTarget.ES2018,
module: ModuleKind.CommonJS,
lib: ['dom', 'es2018'],
}
},
})
compiler.ts.createLanguageService = jest.fn().mockReturnValue(languageService)
languageService.getEmitOutput = jest.fn().mockReturnValue({
outputFiles: [],
emitSkipped: false,
})
return compiler
}
beforeEach(() => {
logTarget.clear()
})
describe('typings', () => {
const compiler = makeCompiler({ tsJestConfig: { tsConfig: false } })
it('should report diagnostics related to typings', () => {
expect(() =>
compiler.compile(
`
const f = (v: number) => v
const t: string = f(5)
const v: boolean = t
`,
'foo.ts',
),
).toThrowErrorMatchingInlineSnapshot(`
"TypeScript diagnostics (customize using \`[jest-config].globals.ts-jest.diagnostics\` option):
foo.ts(3,7): error TS2322: Type 'number' is not assignable to type 'string'.
foo.ts(4,7): error TS2322: Type 'string' is not assignable to type 'boolean'."
`)
})
})
describe('source-maps', () => {
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)
const processed = new ProcessedSource(compiled, __filename)
// const expectedFileName = relativeToRoot(__filename)
const expectedFileName = __filename
expect(processed.outputSourceMaps).toMatchObject({
file: expectedFileName,
sources: [expectedFileName],
sourcesContent: [source],
})
})
})
describe('cache', () => {
const tmp = tempDir('compiler')
const compiler = makeCompiler({
jestConfig: { cache: true, cacheDirectory: tmp },
tsJestConfig: { tsConfig: false },
})
const source = 'console.log("hello")'
it('should use the cache', () => {
const compiled1 = compiler.compile(source, __filename)
expect(logTarget.filteredLines(LogLevels.debug, Infinity)).toMatchInlineSnapshot(`
Array [
"[level:20] readThrough(): cache miss
",
"[level:20] getOutput(): compiling using language service
",
"[level:20] updateMemoryCache()
",
"[level:20] visitSourceFileNode(): hoisting
",
"[level:20] getOutput(): computing diagnostics from language service
",
"[level:20] readThrough(): writing caches
",
]
`)
logTarget.clear()
const compiled2 = compiler.compile(source, __filename)
expect(logTarget.lines).toMatchInlineSnapshot(`
Array [
"[level:20] readThrough(): cache hit
",
]
`)
expect(new ProcessedSource(compiled1, __filename)).toMatchSnapshot()
expect(compiled2).toBe(compiled1)
})
})
describe('isolatedModules', () => {
const compiler = makeCompiler({ tsJestConfig: { isolatedModules: true, tsConfig: false } })
const spy = jest.spyOn(require('typescript'), 'transpileModule')
afterAll(() => {
spy.mockRestore()
})
it('should compile using transpileModule', () => {
const compiled = compiler.compile('export default 42', __filename)
expect(new ProcessedSource(compiled, __filename)).toMatchSnapshot()
expect(spy).toHaveBeenCalled()
})
})
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).toMatchSnapshot()
})
})
describe('getTypeInfo', () => {
const compiler = makeCompiler({ tsJestConfig: { tsConfig: false } })
const source = `
type MyType {
/** the prop 1! */
p1: boolean
}
const val: MyType = {} as any
console.log(val.p1/* <== that */)
`
it('should get correct type info', () => {
const ti = compiler.getTypeInfo(source, __filename, source.indexOf('/* <== that */') - 1)
// before TS 3.1 the comment had an extra tailing space
ti.comment = ti.comment.trim()
expect(ti).toEqual({
comment: 'the prop 1!',
name: '(property) p1: boolean',
})
})
})
describe('Program', () => {
// These preparation steps are needed to make the test work correctly
const tmp = tempDir('compiler')
let compiler = makeFallbackCompiler({
jestConfig: { cache: true, cacheDirectory: tmp },
tsJestConfig: { tsConfig: false },
})
const source = 'console.log("hello")'
it('should compile using Program as fallback', () => {
try {
compiler = makeFallbackCompiler({ tsJestConfig: { tsConfig: false } })
compiler.compile(source, 'test.ts')
} catch (e) {
expect(e.message).toMatchSnapshot('compile-error')
expect(logTarget.filteredLines(LogLevels.debug, Infinity)).toMatchInlineSnapshot(`
Array [
"[level:20] backporting config
",
"[level:20] normalized jest config
",
"[level:20] normalized ts-jest config
",
"[level:20] creating typescript compiler (language service)
",
"[level:20] file caching disabled
",
"[level:20] normalized typescript config
",
"[level:20] creating language service
",
"[level:20] readThrough(): no cache
",
"[level:20] getOutput(): compiling using language service
",
"[level:20] updateMemoryCache()
",
"[level:20] getOutput(): creating Program as fallback for language service
",
"[level:20] getOutput(): compiling using Program
",
"[level:20] getOutput(): computing diagnostics from Program emit result
",
]
`)
}
})
})