Skip to content

Commit

Permalink
refactor: refactor TsJestTransformer
Browse files Browse the repository at this point in the history
- Use `@jest/create-cache-key-function` to create cache key
- Rename interface `ConfigSetItem` -> `CachedConfigSet`
- Rename field `configSetItems` -> `cachedConfigSets`
- Remove `configsFor` and replace with `createOrResolveTransformerCfg`
  • Loading branch information
ahnpnl committed Oct 11, 2020
1 parent f5b0a62 commit b5477b8
Show file tree
Hide file tree
Showing 11 changed files with 316 additions and 473 deletions.
15 changes: 6 additions & 9 deletions e2e/__cases__/ts-jest-checks/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import { createTransformer } from 'ts-jest'
import { readFileSync } from 'fs'
import { ConfigSet } from 'ts-jest/dist/config/config-set'

describe('tsConfig', () => {
it('should have digest and versions', () => {
const tr = createTransformer()
const cs = tr.configsFor(Object.create(null))
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)
})
it('should have digest and versions', () => {
const cs = new ConfigSet(Object.create(null))
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)
})
70 changes: 35 additions & 35 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
},
"homepage": "https://kulshekhar.github.io/ts-jest",
"dependencies": {
"@jest/create-cache-key-function": "^26.5.0",
"@types/jest": "26.x",
"bs-logger": "0.x",
"buffer-from": "1.x",
Expand Down
16 changes: 16 additions & 0 deletions src/__snapshots__/ts-jest-transformer.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`TsJestTransformer process should process file with babel-jest 1`] = `
"foo;
//# "
`;

exports[`TsJestTransformer process should process file with babel-jest 2`] = `
"[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. If you still want Babel to process it, add another entry to the \`transform\` option with value \`babel-jest\` which key matches this type of files.
"
`;

exports[`TsJestTransformer process should process file with babel-jest 3`] = `
"foo;
//# "
`;
2 changes: 1 addition & 1 deletion src/compiler/instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { stringify } from '../utils/json'
/**
* Rely on TypeScript compiled output generation which contains this prefix to point to sourcemap location.
*/
const SOURCE_MAPPING_PREFIX = 'sourceMappingURL='
export const SOURCE_MAPPING_PREFIX = 'sourceMappingURL='

/**
* Update the output remapping the source map.
Expand Down
111 changes: 1 addition & 110 deletions src/config/config-set.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable jest/no-mocks-import */
import type { Transformer } from '@jest/transform'
import { LogLevels, testing } from 'bs-logger'
import { testing } from 'bs-logger'
import { join, resolve } from 'path'
import ts from 'typescript'

Expand Down Expand Up @@ -713,115 +713,6 @@ describe('readTsConfig', () => {
})
})
})

describe('mismatch nodejs version and typescript target', () => {
const logTarget = logTargetMock()
function mismatchTestCaseContent(rawTarget: string | undefined, scriptTarget: ts.ScriptTarget) {
parseConfig.mockImplementation((conf: any) => ({
options: {
...conf,
target: scriptTarget,
},
fileNames: [],
errors: [],
}))
readConfig.mockImplementation((p) => ({ config: { path: p, compilerOptions: { target: rawTarget } } }))

cs.readTsConfig()
}

describe.each([
{ jestConfig: { rootDir: '/root', cwd: '/cwd' } as any, tsJestConfig: { babelConfig: true } },
{ jestConfig: { rootDir: '/root', cwd: '/cwd' } as any },
])('toggle warning message for users who are using ts-jest with babel or without babel', (config) => {
const shouldAction = config.tsJestConfig?.babelConfig ? `shouldn't` : 'should'

beforeEach(() => {
logTarget.clear()
cs = createConfigSet(config)
findConfig.mockImplementation((p: string) => `${p}/tsconfig.json`)
})

afterEach(() => {
findConfig.mockClear()
parseConfig.mockClear()
readConfig.mockClear()
})

/**
* It seems like not possible to mock process.version so the condition here is needed
*/
if (process.version.startsWith('v10')) {
it(
`${shouldAction} show warning message when nodejs version is 10 and typescript target is higher than es2018` +
` with tsconfig contains target`,
() => {
mismatchTestCaseContent('es2019', ts.ScriptTarget.ES2019)
// eslint-disable-next-line
config.tsJestConfig?.babelConfig
? expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toBeUndefined()
: // expect.toEqual gives weird result here so toContain is workaround for it.
expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toContain(
'[level:40] There is a mismatch between your ' +
`NodeJs version ${process.version} and your TypeScript target es2019. This might lead to some unexpected errors ` +
'when running tests with `ts-jest`. To fix this, you can check https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping',
)
},
)

it(
`${shouldAction} show warning message when nodejs version is 10 and typescript target is higher than es2018` +
` with tsconfig doesn't contain target`,
() => {
mismatchTestCaseContent(undefined, ts.ScriptTarget.ES2019)
// eslint-disable-next-line
config.tsJestConfig?.babelConfig
? expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toBeUndefined()
: // expect.toEqual gives weird result here so toContain is workaround for it.
expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toContain(
'[level:40] There is a mismatch between your ' +
`NodeJs version ${process.version} and your TypeScript target es2019. This might lead to some unexpected errors ` +
'when running tests with `ts-jest`. To fix this, you can check https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping',
)
},
)
} else {
it(
`${shouldAction} show warning message when nodejs version is 12 and typescript target is higher than es2019` +
` with tsconfig contains target`,
() => {
mismatchTestCaseContent('es2020', ts.ScriptTarget.ES2020)
// eslint-disable-next-line
config.tsJestConfig?.babelConfig
? expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toBeUndefined()
: // expect.toEqual gives weird result here so toContain is workaround for it.
expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toContain(
'[level:40] There is a mismatch between your ' +
`NodeJs version ${process.version} and your TypeScript target es2020. This might lead to some unexpected errors ` +
'when running tests with `ts-jest`. To fix this, you can check https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping',
)
},
)

it(
`${shouldAction} show warning message when nodejs version is 12 and typescript target is higher than es2019` +
` with tsconfig doesn't target`,
() => {
mismatchTestCaseContent(undefined, ts.ScriptTarget.ES2020)
// eslint-disable-next-line
config.tsJestConfig?.babelConfig
? expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toBeUndefined()
: // expect.toEqual gives weird result here so toContain is workaround for it.
expect(logTarget.filteredLines(LogLevels.warn, Infinity)[0]).toContain(
'[level:40] There is a mismatch between your ' +
`NodeJs version ${process.version} and your TypeScript target es2020. This might lead to some unexpected errors ` +
'when running tests with `ts-jest`. To fix this, you can check https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping',
)
},
)
}
})
})
}) // readTsConfig

describe('versions', () => {
Expand Down
8 changes: 6 additions & 2 deletions src/config/config-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* version of the `jest.ProjectConfig`, and then later it calls `process()`
* with the complete, object version of it.
*/
import type { TransformedSource } from '@jest/transform'
import type { Config } from '@jest/types'
import { LogContexts, Logger } from 'bs-logger'
import { existsSync, readFileSync } from 'fs'
Expand Down Expand Up @@ -38,7 +39,6 @@ import type {
TsCompiler,
TsJestConfig,
TsJestGlobalOptions,
TsJestHooksMap,
TTypeScript,
} from '../types'
import { backportJestConfig } from '../utils/backports'
Expand Down Expand Up @@ -67,12 +67,15 @@ interface AstTransformerObj<T = Record<string, unknown>> {
transformModule: AstTransformerDesc
options?: T
}

interface AstTransformer {
before: AstTransformerObj[]
after?: AstTransformerObj[]
afterDeclarations?: AstTransformerObj[]
}
interface TsJestHooksMap {
afterProcess?(args: any[], result: string | TransformedSource): string | TransformedSource | void
}

/**
* @internal
*/
Expand Down Expand Up @@ -889,6 +892,7 @@ export class ConfigSet {
const nodeJsVer = process.version
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const compilationTarget = result.options.target!
/* istanbul ignore next (cover by e2e) */
if (
!this.tsJest.babelConfig &&
((nodeJsVer.startsWith('v10') && compilationTarget > ScriptTarget.ES2018) ||
Expand Down
Loading

0 comments on commit b5477b8

Please sign in to comment.