Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(config): compute cache key without reading package.json #1893

Merged
merged 1 commit into from
Aug 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/config/__snapshots__/config-set.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`cacheKey should be a string 1`] = `"{\\"digest\\":\\"a0d51ca854194df8191d0e65c0ca4730f510f332\\",\\"jest\\":{\\"__backported\\":true,\\"globals\\":{}},\\"projectDepVersions\\":{\\"dev\\":\\"1.2.5\\",\\"opt\\":\\"1.2.3\\",\\"peer\\":\\"1.2.4\\",\\"std\\":\\"1.2.6\\"},\\"transformers\\":[\\"hoisting-jest-mock@1\\"],\\"tsJest\\":{\\"compiler\\":\\"typescript\\",\\"diagnostics\\":{\\"ignoreCodes\\":[6059,18002,18003],\\"pretty\\":true,\\"throws\\":true},\\"isolatedModules\\":false,\\"packageJson\\":{\\"kind\\":\\"file\\"},\\"transformers\\":{},\\"tsConfig\\":{\\"kind\\":\\"file\\",\\"value\\":\\"\\"}},\\"tsconfig\\":{\\"options\\":{\\"configFilePath\\":\\"\\",\\"declaration\\":false,\\"inlineSourceMap\\":false,\\"inlineSources\\":true,\\"module\\":1,\\"noEmit\\":false,\\"removeComments\\":false,\\"sourceMap\\":true,\\"target\\":1,\\"types\\":[]},\\"raw\\":{\\"compileOnSave\\":false,\\"compilerOptions\\":{\\"composite\\":true,\\"declaration\\":true,\\"types\\":[]},\\"exclude\\":[\\"foo/**/*\\"],\\"include\\":[\\"bar/**/*\\"]}}}"`;
exports[`cacheKey should be a string 1`] = `"{\\"digest\\":\\"a0d51ca854194df8191d0e65c0ca4730f510f332\\",\\"jest\\":{\\"__backported\\":true,\\"globals\\":{}},\\"transformers\\":[\\"hoisting-jest-mock@1\\"],\\"tsJest\\":{\\"compiler\\":\\"typescript\\",\\"diagnostics\\":{\\"ignoreCodes\\":[6059,18002,18003],\\"pretty\\":true,\\"throws\\":true},\\"isolatedModules\\":false,\\"packageJson\\":{\\"kind\\":\\"file\\"},\\"transformers\\":{},\\"tsConfig\\":{\\"kind\\":\\"file\\",\\"value\\":\\"\\"}},\\"tsconfig\\":{\\"options\\":{\\"configFilePath\\":\\"\\",\\"declaration\\":false,\\"inlineSourceMap\\":false,\\"inlineSources\\":true,\\"module\\":1,\\"noEmit\\":false,\\"removeComments\\":false,\\"sourceMap\\":true,\\"target\\":1,\\"types\\":[]},\\"raw\\":{\\"compileOnSave\\":false,\\"compilerOptions\\":{\\"composite\\":true,\\"declaration\\":true,\\"types\\":[]},\\"exclude\\":[\\"foo/**/*\\"],\\"include\\":[\\"bar/**/*\\"]}}}"`;

exports[`isTestFile should return a boolean value whether the file matches test pattern 1`] = `true`;

Expand All @@ -20,9 +20,6 @@ Object {
"globals": Object {},
"name": undefined,
},
"projectDepVersions": Object {
"some-module": "1.2.3",
},
"transformers": Array [
"hoisting-jest-mock@1",
],
Expand Down
77 changes: 2 additions & 75 deletions src/config/config-set.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { mocked } from '../util'
import { IGNORE_DIAGNOSTIC_CODES, MATCH_NOTHING, TS_JEST_OUT_DIR } from './config-set'
// eslint-disable-next-line no-duplicate-imports
import type { ConfigSet } from './config-set'
import { Deprecations, Errors, interpolate } from '../util/messages'
import { Deprecations } from '../util/messages'

jest.mock('../util/backports')
jest.mock('../index')
Expand Down Expand Up @@ -809,13 +809,7 @@ describe('tsCacheDir', () => {
const cacheDir = join(process.cwd(), cacheName)
const partialTsJestCacheDir = join(cacheDir, 'ts-jest')

it.each([
undefined,
Object.create(null),
{ 'ts-jest': { packageJson: undefined } },
{ 'ts-jest': { packageJson: { name: 'foo' } } },
{ 'ts-jest': { packageJson: 'src/__mocks__/package-foo.json' } },
])(
it.each([undefined, Object.create(null)])(
'should return value from which is the combination of ts jest config and jest config when running test with cache',
(data) => {
expect(
Expand All @@ -832,73 +826,6 @@ describe('tsCacheDir', () => {
},
)

it('should throw error when running test with cache and cannot resolve package.json path', () => {
const packageJsonPath = 'src/__mocks__/not-exist.json'

expect(
() =>
createConfigSet({
jestConfig: {
cache: true,
cacheDirectory: cacheDir,
globals: {
'ts-jest': { packageJson: packageJsonPath },
},
},
resolve: null,
}).tsCacheDir,
).toThrowError(
new Error(
interpolate(Errors.FileNotFound, {
inputPath: 'src/__mocks__/not-exist.json',
resolvedPath: join(process.cwd(), packageJsonPath),
}),
),
)
})

it(
'should return value and show warning when running test with cache and package.json path is' +
' resolved but the path does not exist',
() => {
const packageJsonPath = 'src/__mocks__/not-exist.json'
const logger = testing.createLoggerMock()

expect(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
createConfigSet({
jestConfig: {
cache: true,
cacheDirectory: cacheDir,
globals: {
'ts-jest': { packageJson: packageJsonPath },
},
},
logger,
}).tsCacheDir!.indexOf(partialTsJestCacheDir),
).toEqual(0)
expect(logger.target.lines[2]).toMatchInlineSnapshot(`
"[level:40] Unable to find the root of the project where ts-jest has been installed.
"
`)

logger.target.clear()
},
)

it('should return value from root packageJson when running test with cache and real path rootDir is the same as tsJest root', () => {
expect(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
createConfigSet({
jestConfig: {
cache: true,
cacheDirectory: cacheDir,
},
resolve: null,
}).tsCacheDir!.indexOf(partialTsJestCacheDir),
).toEqual(0)
})

it('should return undefined when running test without cache', () => {
expect(createConfigSet({ resolve: null }).tsCacheDir).toBeUndefined()
})
Expand Down
64 changes: 1 addition & 63 deletions src/config/config-set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
*/
import type { Config } from '@jest/types'
import { LogContexts, Logger } from 'bs-logger'
import { existsSync, readFileSync, realpathSync } from 'fs'
import { existsSync, readFileSync } from 'fs'
import { globsToMatcher } from 'jest-util'
import json5 = require('json5')
import { dirname, extname, isAbsolute, join, normalize, resolve } from 'path'
Expand Down Expand Up @@ -128,66 +128,6 @@ const toDiagnosticCodeList = (items: any, into: number[] = []): number[] => {
}

export class ConfigSet {
/**
* @internal
*/
@Memoize()
private get projectPackageJson(): Record<string, any> {
const {
tsJest: { packageJson },
} = this
if (packageJson) {
if (packageJson.kind === 'inline') {
return packageJson.value
} else if (packageJson.kind === 'file' && packageJson.value) {
const path = this.resolvePath(packageJson.value)
if (existsSync(path)) {
return require(path)
}

this.logger.warn(Errors.UnableToFindProjectRoot)

return {}
}
}
const tsJestRoot = resolve(__dirname, '..', '..')
let pkgPath = resolve(tsJestRoot, '..', '..', 'package.json')
if (existsSync(pkgPath)) {
return require(pkgPath)
}
if (realpathSync(this.rootDir) === realpathSync(tsJestRoot)) {
pkgPath = resolve(tsJestRoot, 'package.json')
if (existsSync(pkgPath)) {
return require(pkgPath)
}
}

this.logger.warn(Errors.UnableToFindProjectRoot)

return {}
}

/**
* @internal
*/
@Memoize()
private get projectDependencies(): Record<string, string> {
const { projectPackageJson: pkg } = this
const names = Object.keys({
...pkg.optionalDependencies,
...pkg.peerDependencies,
...pkg.devDependencies,
...pkg.dependencies,
})

return names.reduce((map, name) => {
const version = getPackageVersion(name)
if (version) map[name] = version

return map
}, {} as Record<string, string>)
}

/**
* @internal
*/
Expand Down Expand Up @@ -681,7 +621,6 @@ export class ConfigSet {
stringify({
version: this.compilerModule.version,
digest: this.tsJestDigest,
dependencies: this.projectDependencies,
compiler: this.tsJest.compiler,
compilerOptions: this.parsedTsConfig.options,
isolatedModules: this.tsJest.isolatedModules,
Expand Down Expand Up @@ -770,7 +709,6 @@ export class ConfigSet {

return new JsonableValue({
versions: this.versions,
projectDepVersions: this.projectDependencies,
digest: this.tsJestDigest,
transformers: Object.values(this.astTransformers)
.reduce((acc, val) => acc.concat(val), [])
Expand Down