Skip to content

Commit

Permalink
Merge branch 'master' into patch-1
Browse files Browse the repository at this point in the history
  • Loading branch information
72636c authored Nov 26, 2021
2 parents 8598084 + 365812c commit 248e13f
Show file tree
Hide file tree
Showing 9 changed files with 207 additions and 30 deletions.
7 changes: 7 additions & 0 deletions .changeset/funny-maps-rest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"skuba": minor
---

deps: Prettier 2.5

This includes TypeScript 4.5 support. See the [release notes](https://prettier.io/blog/2021/11/25/2.5.0.html) for more information.
2 changes: 1 addition & 1 deletion .changeset/gold-rats-burn.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ deps: TypeScript 4.5

This major release includes breaking changes. See the [announcement](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/) for more information.

Note that new syntax in TypeScript 4.5 is not yet supported by ESLint and Prettier.
Note that new syntax in TypeScript 4.5 is not yet supported by ESLint.
7 changes: 7 additions & 0 deletions .changeset/mighty-eagles-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"skuba": minor
---

jest: Support `tsconfig.json` paths

Module aliases other than `src` are now supported in `skuba test`. Our Jest preset includes a dynamic `moduleNameMapper` that reads the `paths` compiler option from your `tsconfig.json`.
30 changes: 6 additions & 24 deletions jest-preset.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,14 @@
const { defaults: tsJestDefaults } = require('ts-jest/presets');
const { defaults } = require('ts-jest/presets');

const TS_JEST_NAME = 'ts-jest';

/**
* Resolved path of the `ts-jest` preset.
*
* This allows Jest to resolve the preset even if it is installed to a nested
* `./node_modules/skuba/node_modules/ts-jest` directory.
*/
const TS_JEST_PATH = require.resolve(TS_JEST_NAME);

// Rewrite `ts-jest` transformations using our resolved `TS_JEST_PATH`.
const tsJestTransform = Object.fromEntries(
Object.entries(tsJestDefaults.transform).map(([key, value]) => [
key,
value === TS_JEST_NAME ? TS_JEST_PATH : value,
]),
);
const { createModuleNameMapper } = require('./jest/moduleNameMapper');
const { transform } = require('./jest/transform');

/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
...tsJestDefaults,
...defaults,

transform: tsJestTransform,
moduleNameMapper: createModuleNameMapper(),
transform,

collectCoverageFrom: [
'**/*.ts',
Expand All @@ -35,10 +21,6 @@ module.exports = {
'!<rootDir>/jest.*.ts',
],
coverageDirectory: 'coverage',
moduleNameMapper: {
'^src$': '<rootDir>/src',
'^src/(.+)$': '<rootDir>/src/$1',
},
testEnvironment: 'node',
testPathIgnorePatterns: [
'/node_modules.*/',
Expand Down
86 changes: 86 additions & 0 deletions jest/moduleNameMapper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
const path = require('path');

const { pathsToModuleNameMapper } = require('ts-jest/utils');
const {
sys,
findConfigFile,
readConfigFile,
parseJsonConfigFileContent,
} = require('typescript');

/**
* Set a default `src` module alias for backward compatibility.
*
* TODO: drop this default in skuba v4.
*/
const DEFAULT_PATHS = { src: ['src'], 'src/*': ['src/*'] };

/**
* @returns {unknown}
*/
const getConfigFromDisk = () => {
const filename =
findConfigFile('.', sys.fileExists.bind(this)) || 'tsconfig.json';

return readConfigFile(filename, sys.readFile.bind(this)).config;
};

module.exports.createModuleNameMapper = (getConfig = getConfigFromDisk) => {
try {
const json = getConfig();

const parsedConfig = parseJsonConfigFileContent(json, sys, '.');

const paths = Object.fromEntries(
Object.entries(parsedConfig.options.paths ?? DEFAULT_PATHS).flatMap(
([key, values]) => [
// Pass through the input path entry almost verbatim.
// We trim a trailing slash because TypeScript allows `import 'src'`
// to be resolved by the alias `src/`, but Jest's mapper does not.
[
key.replace(/\/$/, ''),
values.map((value) => value.replace(/\/$/, '')),
],
// Append a variant of the input path entry.
// As TypeScript allows both `import 'src'` and `import 'src/nested'`
// to be resolved by the alias `src/*` (and likewise for plain `src`),
// we need to seed two Jest mappings per path.
...(key.endsWith('/*')
? [
[
// Given a path `src/*`, seed an extra `src`.
key.replace(/\/\*$/, ''),
values.map((value) => value.replace(/\/\*$/, '')),
],
]
: [
[
// Given a path `src`, seed an extra `src/*`.
path.join(key, '*'),
values.map((value) => path.join(value, '*')),
],
]),
],
),
);

const prefix = path.join('<rootDir>', parsedConfig.options.baseUrl || '.');

const moduleNameMapper = pathsToModuleNameMapper(paths, { prefix });

// Normalise away any `..`s that may crop up from `baseUrl` usage.
// For example, a `baseUrl` of `src` and a path of `../cli` will result in
// `<rootDir>/src/../cli`, which can be normalised to `<rootDir>/cli`.
return Object.fromEntries(
Object.entries(moduleNameMapper).map(([key, values]) => [
key,
Array.isArray(values)
? values.map((value) => path.normalize(value))
: path.normalize(values),
]),
);
} catch {
// Bail out here to support zero-config mode.
return pathsToModuleNameMapper(DEFAULT_PATHS, { prefix: '<rootDir>' });
}
};
75 changes: 75 additions & 0 deletions jest/moduleNameMapper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { createModuleNameMapper } from './moduleNameMapper';

describe('moduleNameMapper', () => {
const act = (paths?: unknown, baseUrl?: string) =>
createModuleNameMapper(() => ({
compilerOptions: {
baseUrl,
paths,
},
}));

it('expands wildcard paths', () =>
expect(act({ 'src/*': ['src/*'], 'lib/wip/*': ['lib/wip/*'] }))
.toMatchInlineSnapshot(`
Object {
"^lib/wip$": "<rootDir>/lib/wip",
"^lib/wip/(.*)$": "<rootDir>/lib/wip/$1",
"^src$": "<rootDir>/src",
"^src/(.*)$": "<rootDir>/src/$1",
}
`));

it('expands non-wildcard paths', () =>
expect(act({ cli: ['cli'], 'src/': ['src/'] })).toMatchInlineSnapshot(`
Object {
"^cli$": "<rootDir>/cli",
"^cli/(.*)$": "<rootDir>/cli/$1",
"^src$": "<rootDir>/src",
"^src/(.*)$": "<rootDir>/src/$1",
}
`));

it('expands duplicate asymmetric paths', () =>
expect(
act({
jquery: ['node_modules/jquery/dist/jquery'],
'jquery/*': ['node_modules/jquery/dist/jquery/*'],
}),
).toMatchInlineSnapshot(`
Object {
"^jquery$": "<rootDir>/node_modules/jquery/dist/jquery",
"^jquery/(.*)$": "<rootDir>/node_modules/jquery/dist/jquery/$1",
}
`));

it('respects a base URL', () =>
expect(act({ cli: ['../cli'], 'app/*': ['app/*'] }, 'src'))
.toMatchInlineSnapshot(`
Object {
"^app$": "<rootDir>/src/app",
"^app/(.*)$": "<rootDir>/src/app/$1",
"^cli$": "<rootDir>/cli",
"^cli/(.*)$": "<rootDir>/cli/$1",
}
`));

it('respects no paths', () =>
expect(act({})).toMatchInlineSnapshot(`Object {}`));

it('falls back on undefined paths', () =>
expect(act(undefined)).toMatchInlineSnapshot(`
Object {
"^src$": "<rootDir>/src",
"^src/(.*)$": "<rootDir>/src/$1",
}
`));

it('falls back on invalid config', () =>
expect(act('INVALID')).toMatchInlineSnapshot(`
Object {
"^src$": "<rootDir>/src",
"^src/(.*)$": "<rootDir>/src/$1",
}
`));
});
19 changes: 19 additions & 0 deletions jest/transform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const { defaults } = require('ts-jest/presets');

const TS_JEST_NAME = 'ts-jest';

/**
* Resolved path of the `ts-jest` preset.
*
* This allows Jest to resolve the preset even if it is installed to a nested
* `./node_modules/skuba/node_modules/ts-jest` directory.
*/
const TS_JEST_PATH = require.resolve(TS_JEST_NAME);

// Rewrite `ts-jest` transformations using our resolved `TS_JEST_PATH`.
module.exports.transform = Object.fromEntries(
Object.entries(defaults.transform).map(([key, value]) => [
key,
value === TS_JEST_NAME ? TS_JEST_PATH : value,
]),
);
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"typings": "lib/index.d.ts",
"files": [
"config/**/*",
"jest/**/*",
"lib*/**/*.d.ts",
"lib*/**/*.js",
"lib*/**/*.js.map",
Expand Down Expand Up @@ -86,7 +87,7 @@
"npm-run-path": "^4.0.1",
"npm-which": "^3.0.1",
"picomatch": "^2.2.2",
"prettier": "~2.4.1",
"prettier": "~2.5.0",
"read-pkg-up": "^7.0.1",
"runtypes": "^6.0.0",
"semantic-release": "^17.4.7",
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6701,10 +6701,10 @@ prettier@^1.19.1:
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb"
integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==

prettier@~2.4.1:
version "2.4.1"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.4.1.tgz#671e11c89c14a4cfc876ce564106c4a6726c9f5c"
integrity sha512-9fbDAXSBcc6Bs1mZrDYb3XKzDLm4EXXL9sC1LqKP5rZkT6KRr/rf9amVUcODVXgguK/isJz0d0hP72WeaKWsvA==
prettier@~2.5.0:
version "2.5.0"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.5.0.tgz#a6370e2d4594e093270419d9cc47f7670488f893"
integrity sha512-FM/zAKgWTxj40rH03VxzIPdXmj39SwSjwG0heUcNFwI+EMZJnY93yAiKXM3dObIKAM5TA88werc8T/EwhB45eg==

pretty-format@^27.0.0, pretty-format@^27.3.1:
version "27.3.1"
Expand Down

0 comments on commit 248e13f

Please sign in to comment.