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

feat: allow passing TS config loader options #15234

Merged
merged 5 commits into from
Aug 4, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
- `[jest-config]` [**BREAKING**] Update `testMatch` and `testRegex` default option for supporting `mjs`, `cjs`, `mts`, and `cts` ([#14584](https://github.com/jestjs/jest/pull/14584))
- `[jest-config]` Loads config file from provided path in `package.json` ([#14044](https://github.com/facebook/jest/pull/14044))
- `[jest-config]` Allow loading `jest.config.cts` files ([#14070](https://github.com/facebook/jest/pull/14070))
- `[jest-config]` Added an option to disable `ts-node` typechecking ([#15161](https://github.com/jestjs/jest/pull/15161))
- `[jest-config]` Show `rootDir` in error message when a `preset` fails to load ([#15194](https://github.com/jestjs/jest/pull/15194))
- `[jest-config]` Support loading TS config files using `esbuild-register` via docblock loader ([#15190](https://github.com/jestjs/jest/pull/15190))
- `[jest-config]` allow passing TS config loader options via docblock comment ([#15234](https://github.com/jestjs/jest/pull/15234))
- `[@jest/core]` Group together open handles with the same stack trace ([#13417](https://github.com/jestjs/jest/pull/13417), & [#14789](https://github.com/jestjs/jest/pull/14789))
- `[@jest/core]` Add `perfStats` to surface test setup overhead ([#14622](https://github.com/jestjs/jest/pull/14622))
- `[@jest/core]` [**BREAKING**] Changed `--filter` to accept an object with shape `{ filtered: Array<string> }` to match [documentation](https://jestjs.io/docs/cli#--filterfile) ([#13319](https://github.com/jestjs/jest/pull/13319))
Expand Down
15 changes: 14 additions & 1 deletion docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,20 @@ const config: Config = {
export default config;
```

If you are using `ts-node`, you can set `JEST_CONFIG_TRANSPILE_ONLY` environment variable to `true` (case insensitive) to read configuration files without typechecking.
You can also pass options to the loader, for instance to enable `transpileOnly`.

```ts title="jest.config.ts"
/** @jest-config-loader ts-node */
/** @jest-config-loader-options {"transpileOnly": true} */

import type {Config} from 'jest';

const config: Config = {
verbose: true,
};

export default config;
```

:::

Expand Down
7 changes: 2 additions & 5 deletions e2e/__tests__/jest.config.ts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ const jestTypesExists = fs.existsSync(jestTypesPath);
writeFiles(DIR, {
'__tests__/a-giraffe.js': "test('giraffe', () => expect(1).toBe(1));",
'jest.config.ts': `
/**@jest-config-loader-options {"transpileOnly":${!!skipTypeCheck}}*/
import {Config} from 'jest';
const config: Config = { testTimeout: "10000" };
export default config;
Expand All @@ -95,11 +96,7 @@ const jestTypesExists = fs.existsSync(jestTypesPath);
"TS2322: Type 'string' is not assignable to type 'number'.";
const runtimeErrorString = 'Option "testTimeout" must be of type:';

const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false'], {
env: {
JEST_CONFIG_TRANSPILE_ONLY: skipTypeCheck ? 'true' : undefined,
},
});
const {stderr, exitCode} = runJest(DIR, ['-w=1', '--ci=false']);

if (skipTypeCheck) {
expect(stderr).not.toMatch(typeErrorString);
Expand Down
11 changes: 9 additions & 2 deletions packages/jest-config/src/readConfigFileAndSetRootDir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {isNativeError} from 'util/types';
import * as fs from 'graceful-fs';
import parseJson = require('parse-json');
import stripJsonComments = require('strip-json-comments');
import type {RegisterOptions} from 'ts-node';
import type {Config} from '@jest/types';
import {extract, parse} from 'jest-docblock';
import {interopRequireDefault, requireOrImportModule} from 'jest-util';
Expand Down Expand Up @@ -89,13 +90,19 @@ export default async function readConfigFileAndSetRootDir(
}

// Load the TypeScript configuration
let extraTSLoaderOptions: RegisterOptions;
SimenB marked this conversation as resolved.
Show resolved Hide resolved

const loadTSConfigFile = async (
configPath: string,
): Promise<Config.InitialOptions> => {
// Get registered TypeScript compiler instance
const docblockPragmas = parse(extract(fs.readFileSync(configPath, 'utf8')));
const tsLoader = docblockPragmas['jest-config-loader'] || 'ts-node';
Copy link
Contributor Author

@k-rajat19 k-rajat19 Aug 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we also change this default behavior of using ts-node if no loader is passed in a separate PR? it will be a breaking change though

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's a separate thing, yeah. happy to take a PR

const docblockTSLoaderOptions = docblockPragmas['jest-config-loader-options'];

if (typeof docblockTSLoaderOptions === 'string') {
extraTSLoaderOptions = JSON.parse(docblockTSLoaderOptions);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these should be passed to esbuild-register as well

}
if (Array.isArray(tsLoader)) {
throw new TypeError(
`Jest: You can only define a single loader through docblocks, got "${tsLoader.join(
Expand Down Expand Up @@ -143,8 +150,8 @@ async function registerTsLoader(loader: TsLoaderModule): Promise<TsLoader> {
moduleTypes: {
'**': 'cjs',
},
transpileOnly:
process.env.JEST_CONFIG_TRANSPILE_ONLY?.toLowerCase() === 'true',
SimenB marked this conversation as resolved.
Show resolved Hide resolved
swc: extraTSLoaderOptions?.swc,
transpileOnly: extraTSLoaderOptions?.transpileOnly,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of setting these two, can we just spread the config passed?

i.e.

tsLoader.register({
  compilerOptions: {
    module: 'CommonJS',
  },
  moduleTypes: {
    '**': 'cjs',
  },
  ...extraTSLoaderOptions,
});

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought the same but not sure if it's a good idea to expose all options or not, done 4223489

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if people misconfigure, that's on them. I think exposing the API is better than having to expose more in the future

});
} else if (loader === 'esbuild-register') {
const tsLoader = await import(
Expand Down
Loading