Skip to content

Commit

Permalink
refactor(config): convert getters to methods/properties in ConfigSet (
Browse files Browse the repository at this point in the history
  • Loading branch information
ahnpnl committed Dec 13, 2020
1 parent c277858 commit 2b6c1af
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 110 deletions.
19 changes: 15 additions & 4 deletions src/__helpers__/fakers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ export function filePath(relPath: string): string {

export const rootDir = filePath('')

const defaultTestRegex = ['(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.[jt]sx?$']
const defaultTestMatch = ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)']

function getJestConfig<T extends Config.ProjectConfig>(
options?: Partial<Config.InitialOptions | Config.ProjectConfig>,
tsJestOptions?: TsJestGlobalOptions,
Expand Down Expand Up @@ -47,7 +50,16 @@ export function createConfigSet({
resolve?: ((path: string) => string) | null
[key: string]: any
} = {}): ConfigSet {
const cs = new ConfigSet(getJestConfig(jestConfig, tsJestConfig), logger)
const jestCfg = getJestConfig(jestConfig, tsJestConfig)
const cs = new ConfigSet(
{
...jestCfg,
testMatch: jestConfig?.testMatch ? [...jestConfig.testMatch, ...defaultTestMatch] : defaultTestMatch,
testRegex: jestConfig?.testRegex ? [...jestConfig.testRegex, ...defaultTestRegex] : defaultTestRegex,
extensionsToTreatAsEsm: jestCfg.extensionsToTreatAsEsm ?? [],
},
logger,
)
if (resolve) {
cs.resolvePath = resolve
}
Expand Down Expand Up @@ -76,12 +88,11 @@ export function makeCompiler(
...(tsJestConfig.diagnostics as any),
pretty: false,
}
const defaultTestRegex = ['(/__tests__/.*|(\\\\.|/)(test|spec))\\\\.[jt]sx?$']
const defaultTestMatch = ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)']
jestConfig = {
...jestConfig,
extensionsToTreatAsEsm: jestConfig?.extensionsToTreatAsEsm ?? [],
testMatch: jestConfig?.testMatch ? [...jestConfig.testMatch, ...defaultTestMatch] : defaultTestMatch,
testRegex: jestConfig?.testRegex ? [...defaultTestRegex, ...jestConfig.testRegex] : defaultTestRegex,
testRegex: jestConfig?.testRegex ? [...jestConfig.testRegex, ...defaultTestRegex] : defaultTestRegex,
}
const cs = createConfigSet({ jestConfig, tsJestConfig, parentConfig, resolve: null })

Expand Down
11 changes: 0 additions & 11 deletions src/config/config-set.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,17 +396,6 @@ describe('tsJestDigest', () => {
})
}) // tsJestDigest

describe('hooks', () => {
it('should return empty object when environment variable TS_JEST_HOOKS is undefined', () => {
expect(createConfigSet().hooks).toEqual({})
})

it('should return value when environment variable TS_JEST_HOOKS is defined', () => {
process.env.TS_JEST_HOOKS = './foo'
expect(createConfigSet().hooks).toBeDefined()
})
}) // hooks

describe('isTestFile', () => {
it.each([
{
Expand Down
106 changes: 34 additions & 72 deletions src/config/config-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
* 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 +37,6 @@ import { backportJestConfig } from '../utils/backports'
import { importer } from '../utils/importer'
import { stringify } from '../utils/json'
import { rootLogger } from '../utils/logger'
import { Memoize } from '../utils/memoize'
import { Errors, ImportReasons, interpolate } from '../utils/messages'
import { normalizeSlashes } from '../utils/normalize-slashes'
import { sha1 } from '../utils/sha1'
Expand All @@ -49,10 +47,6 @@ import { TSError } from '../utils/ts-error'
*/
export const MY_DIGEST: string = readFileSync(resolve(__dirname, '..', '..', '.ts-jest-digest'), 'utf8')

interface TsJestHooksMap {
afterProcess?(args: any[], result: string | TransformedSource): string | TransformedSource | void
}

/**
* @internal
*/
Expand Down Expand Up @@ -109,6 +103,10 @@ const toDiagnosticCodeList = (items: (string | number)[], into: number[] = []):
}

export class ConfigSet {
/**
* Use by e2e, don't mark as internal
*/
readonly tsJestDigest = MY_DIGEST
readonly logger: Logger
readonly compilerModule: TTypeScript
readonly isolatedModules: boolean
Expand All @@ -124,11 +122,11 @@ export class ConfigSet {
/**
* @internal
*/
private _babelConfig: BabelConfig | undefined
babelConfig: BabelConfig | undefined
/**
* @internal
*/
private _babelJestTransformers: BabelJestTransformer | undefined
babelJestTransformer: BabelJestTransformer | undefined
/**
* @internal
*/
Expand All @@ -137,6 +135,8 @@ export class ConfigSet {
* @internal
*/
private _stringifyContentRegExp: RegExp | undefined
private readonly _matchablePatterns: (string | RegExp)[]
private readonly _isMatch: (str: Config.Path) => boolean
protected _overriddenCompilerOptions: Partial<CompilerOptions> = {
// we handle sourcemaps this way and not another
sourceMap: true,
Expand Down Expand Up @@ -187,6 +187,20 @@ export class ConfigSet {
this._backportJestCfg()
this._setupTsJestCfg(options)
this._resolveTsCacheDir()
this._matchablePatterns = [...this._jestCfg.testMatch, ...this._jestCfg.testRegex].filter(
(pattern) =>
/**
* jest config testRegex doesn't always deliver the correct RegExp object
* See https://github.com/facebook/jest/issues/9778
*/
pattern instanceof RegExp || typeof pattern === 'string',
)
if (!this._matchablePatterns.length) {
this._matchablePatterns.push(...DEFAULT_JEST_TEST_MATCH)
}
this._isMatch = globsToMatcher(
this._matchablePatterns.filter((pattern: any) => typeof pattern === 'string') as string[],
)
}

/**
Expand All @@ -212,33 +226,33 @@ export class ConfigSet {
if (typeof options.babelConfig === 'string') {
const babelCfgPath = this.resolvePath(options.babelConfig)
if (extname(options.babelConfig) === '.js') {
this._babelConfig = {
this.babelConfig = {
...baseBabelCfg,
...require(babelCfgPath),
}
} else {
this._babelConfig = {
this.babelConfig = {
...baseBabelCfg,
...json5.parse(readFileSync(babelCfgPath, 'utf-8')),
}
}
} else if (typeof options.babelConfig === 'object') {
this._babelConfig = {
this.babelConfig = {
...baseBabelCfg,
...options.babelConfig,
}
} else {
this._babelConfig = baseBabelCfg
this.babelConfig = baseBabelCfg
}

this.logger.debug({ babelConfig: this._babelConfig }, 'normalized babel config via ts-jest option')
this.logger.debug({ babelConfig: this.babelConfig }, 'normalized babel config via ts-jest option')
}
if (!this._babelConfig) {
if (!this.babelConfig) {
this._overriddenCompilerOptions.module = this.compilerModule.ModuleKind.CommonJS
} else {
this._babelJestTransformers = importer
this.babelJestTransformer = importer
.babelJest(ImportReasons.BabelJest)
.createTransformer(this._babelConfig) as BabelJestTransformer
.createTransformer(this.babelConfig) as BabelJestTransformer

this.logger.debug('created babel-jest transformer')
}
Expand Down Expand Up @@ -450,7 +464,7 @@ export class ConfigSet {
const compilationTarget = result.options.target!
/* istanbul ignore next (cover by e2e) */
if (
!this._babelConfig &&
!this.babelConfig &&
((nodeJsVer.startsWith('v10') && compilationTarget > ScriptTarget.ES2018) ||
(nodeJsVer.startsWith('v12') && compilationTarget > ScriptTarget.ES2019))
) {
Expand All @@ -465,62 +479,10 @@ export class ConfigSet {
return result
}

/**
* @internal
*/
get babelConfig(): BabelConfig | undefined {
return this._babelConfig
}

/**
* @internal
*/
get babelJestTransformer(): BabelJestTransformer | undefined {
return this._babelJestTransformers
}

/**
* Use by e2e, don't mark as internal
*/
@Memoize()
// eslint-disable-next-line class-methods-use-this
get tsJestDigest(): string {
return MY_DIGEST
}

/**
* @internal
*/
@Memoize()
get hooks(): TsJestHooksMap {
let hooksFile = process.env.TS_JEST_HOOKS
if (hooksFile) {
hooksFile = resolve(this.cwd, hooksFile)

return importer.tryTheseOr(hooksFile, {})
}

return {}
}

@Memoize()
get isTestFile(): (fileName: string) => boolean {
const matchablePatterns = [...this._jestCfg.testMatch, ...this._jestCfg.testRegex].filter(
(pattern) =>
/**
* jest config testRegex doesn't always deliver the correct RegExp object
* See https://github.com/facebook/jest/issues/9778
*/
pattern instanceof RegExp || typeof pattern === 'string',
isTestFile(fileName: string): boolean {
return this._matchablePatterns.some((pattern) =>
typeof pattern === 'string' ? this._isMatch(fileName) : pattern.test(fileName),
)
if (!matchablePatterns.length) {
matchablePatterns.push(...DEFAULT_JEST_TEST_MATCH)
}
const stringPatterns = matchablePatterns.filter((pattern: any) => typeof pattern === 'string') as string[]
const isMatch = globsToMatcher(stringPatterns)

return (fileName: string) =>
matchablePatterns.some((pattern) => (typeof pattern === 'string' ? isMatch(fileName) : pattern.test(fileName)))
}

shouldStringifyContent(filePath: string): boolean {
Expand Down
42 changes: 21 additions & 21 deletions src/ts-jest-transformer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import { Extension, ResolvedModuleFull } from 'typescript'

import { SOURCE_MAPPING_PREFIX } from './compiler/compiler-utils'
import { TsJestCompiler } from './compiler/ts-jest-compiler'
import { ConfigSet } from './config/config-set'
import { logTargetMock } from './__helpers__/mocks'
import { CACHE_KEY_EL_SEPARATOR, TsJestTransformer } from './ts-jest-transformer'
import type { ResolvedModulesMap } from './types'
import { stringify } from './utils/json'
import { sha1 } from './utils/sha1'
import { VersionCheckers } from './utils/version-checkers'
import { createConfigSet } from './__helpers__/fakers'

const logTarget = logTargetMock()
const cacheDir = join(process.cwd(), 'tmp')
Expand All @@ -31,7 +31,7 @@ beforeEach(() => {
describe('TsJestTransformer', () => {
describe('_configsFor', () => {
test('should return the same config set for same values with jest config string is not in configSetsIndex', () => {
const obj1 = { config: { cwd: '/foo/.', rootDir: '/bar//dummy/..', globals: {} } }
const obj1 = { config: { cwd: '/foo/.', rootDir: '/bar//dummy/..', globals: {}, testMatch: [], testRegex: [] } }
// @ts-expect-error testing purpose
const cs3 = new TsJestTransformer()._configsFor(obj1 as any)

Expand All @@ -40,7 +40,7 @@ describe('TsJestTransformer', () => {
})

test('should return the same config set for same values with jest config string in configSetsIndex', () => {
const obj1 = { config: { cwd: '/foo/.', rootDir: '/bar//dummy/..', globals: {} } }
const obj1 = { config: { cwd: '/foo/.', rootDir: '/bar//dummy/..', globals: {}, testMatch: [], testRegex: [] } }
const obj2 = { ...obj1 }
// @ts-expect-error testing purpose
const cs1 = new TsJestTransformer()._configsFor(obj1 as any)
Expand All @@ -54,11 +54,11 @@ describe('TsJestTransformer', () => {

test(`should not read disk cache with isolatedModules true`, () => {
const tr = new TsJestTransformer()
const cs = new ConfigSet({
testMatch: [],
testRegex: [],
globals: { 'ts-jest': { isolatedModules: true } },
} as any)
const cs = createConfigSet({
jestConfig: {
globals: { 'ts-jest': { isolatedModules: true } },
},
})
const readFileSyncSpy = jest.spyOn(fs, 'readFileSync')

// @ts-expect-error testing purpose
Expand All @@ -71,11 +71,11 @@ describe('TsJestTransformer', () => {

test(`should not read disk cache with isolatedModules false and no jest cache`, () => {
const tr = new TsJestTransformer()
const cs = new ConfigSet({
testMatch: [],
testRegex: [],
globals: { 'ts-jest': { isolatedModules: false } },
} as any)
const cs = createConfigSet({
jestConfig: {
globals: { 'ts-jest': { isolatedModules: false } },
},
})
const readFileSyncSpy = jest.spyOn(fs, 'readFileSync')

// @ts-expect-error testing purpose
Expand All @@ -90,13 +90,13 @@ describe('TsJestTransformer', () => {
const readFileSyncSpy = jest.spyOn(fs, 'readFileSync')
const fileName = 'foo.ts'
const tr = new TsJestTransformer()
const cs = new ConfigSet({
cache: true,
cacheDirectory: cacheDir,
globals: { 'ts-jest': { isolatedModules: false } },
testMatch: [],
testRegex: [],
} as any)
const cs = createConfigSet({
jestConfig: {
cache: true,
cacheDirectory: cacheDir,
globals: { 'ts-jest': { isolatedModules: false } },
},
})
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const tsCacheDir = cs.tsCacheDir!
const depGraphs: ResolvedModulesMap = new Map<string, ResolvedModuleFull | undefined>()
Expand Down Expand Up @@ -191,7 +191,7 @@ describe('TsJestTransformer', () => {
const cacheKey1 = tr.getCacheKey(input.fileContent, input.fileName, {
...input.transformOptions,
config: {
...input.config,
...input.transformOptions.config,
globals: { 'ts-jest': { isolatedModules: true } },
},
})
Expand Down

0 comments on commit 2b6c1af

Please sign in to comment.