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

Upgrade Prettier to v3 #14311

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from 15 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
1,452 changes: 1,452 additions & 0 deletions .yarn/patches/prettier-npm-3.0.0-7ffbcce680.patch

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion e2e/babel-plugin-jest-hoist/__tests__/typescript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import {color} from '../entry';
import type {Color} from '../types';

jest.mock('some-module', () => ({} as Partial<{}>), {virtual: true});
jest.mock('some-module', () => ({}) as Partial<{}>, {virtual: true});

jest.mock('../entry', () => {
const color: Color = 'blue';
Expand Down
5 changes: 5 additions & 0 deletions jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
import {createRequire} from 'module';
const require = createRequire(import.meta.url);

const jestSnapshotIndex = require.resolve('jest-snapshot');
const requireFromSnapshot = createRequire(jestSnapshotIndex);
const prettierPath = requireFromSnapshot.resolve('prettier');

/** @type {import('jest').Config} */
export default {
collectCoverageFrom: [
Expand All @@ -31,6 +35,7 @@ export default {
'website/.*',
'e2e/runtime-internal-module-registry/__mocks__',
],
prettierPath,
projects: ['<rootDir>', '<rootDir>/examples/*/'],
snapshotFormat: {
printBasicPrototype: true,
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"eslint-plugin-jsdoc": "^46.0.0",
"eslint-plugin-local": "link:./.eslintplugin",
"eslint-plugin-markdown": "^3.0.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-prettier": "^5.0.0-alpha.2",
SimenB marked this conversation as resolved.
Show resolved Hide resolved
"execa": "^5.0.0",
"find-process": "^1.4.1",
"glob": "^8.0.0",
Expand All @@ -68,7 +68,7 @@
"node-notifier": "^10.0.0",
"p-limit": "^3.1.0",
"pkg-dir": "^5.0.0",
"prettier": "^2.1.1",
"prettier": "patch:prettier@npm:^3.0.0#./.yarn/patches/prettier-npm-3.0.0-7ffbcce680.patch",
"promise": "^8.0.2",
"read-pkg": "^5.2.0",
"resolve": "^1.20.0",
Expand Down
5 changes: 4 additions & 1 deletion packages/expect/src/asymmetricMatchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ export abstract class AsymmetricMatcher<T>
{
$$typeof = Symbol.for('jest.asymmetricMatcher');

constructor(protected sample: T, protected inverse = false) {}
constructor(
protected sample: T,
protected inverse = false,
) {}

protected getMatcherContext(): MatcherContext {
return {
Expand Down
9 changes: 5 additions & 4 deletions packages/expect/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ export type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;

export type MatcherFunctionWithContext<
Context extends MatcherContext = MatcherContext,
Expected extends Array<any> = [] /** TODO should be: extends Array<unknown> = [] */,
Expected extends
Array<any> = [] /** TODO should be: extends Array<unknown> = [] */,
> = (
this: Context,
actual: unknown,
Expand Down Expand Up @@ -99,9 +100,9 @@ export interface BaseExpect {
}

export type Expect = {
<T = unknown>(actual: T): Matchers<void, T> &
Inverse<Matchers<void, T>> &
PromiseMatchers<T>;
<T = unknown>(
actual: T,
): Matchers<void, T> & Inverse<Matchers<void, T>> & PromiseMatchers<T>;
} & BaseExpect &
AsymmetricMatchers &
Inverse<Omit<AsymmetricMatchers, 'any' | 'anything'>>;
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-core/src/__tests__/watch.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -630,7 +630,7 @@ describe('Watch mode flows', () => {
});

it.each`
ok | option
ok | option
${'✔︎'} | ${'bail'}
${'✖︎'} | ${'changedFilesWithAncestor'}
${'✔︎'} | ${'changedSince'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const getOutputStream = (resolve: (message: string) => void) =>
write(message: string) {
resolve(message);
},
} as NodeJS.WriteStream);
}) as NodeJS.WriteStream;

it('prints the jest version', async () => {
expect.assertions(1);
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-core/src/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -496,8 +496,8 @@ const checkForConflicts = (
.join(' and ');
error = `
Watch plugins ${plugins} both attempted to register key ${chalk.bold.red(
`<${key}>`,
)}.
`<${key}>`,
)}.
Please change the key configuration for one of the conflicting plugins to avoid overlap.`.trim();
}

Expand Down
19 changes: 11 additions & 8 deletions packages/jest-each/src/table/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,16 +60,19 @@ const formatTitle = (
rowIndex: number,
): string =>
row
.reduce<string>((formattedTitle, value) => {
const [placeholder] = getMatchingPlaceholders(formattedTitle);
const normalisedValue = normalisePlaceholderValue(value);
if (!placeholder) return formattedTitle;
.reduce<string>(
(formattedTitle, value) => {
const [placeholder] = getMatchingPlaceholders(formattedTitle);
const normalisedValue = normalisePlaceholderValue(value);
if (!placeholder) return formattedTitle;

if (placeholder === PRETTY_PLACEHOLDER)
return interpolatePrettyPlaceholder(formattedTitle, normalisedValue);
if (placeholder === PRETTY_PLACEHOLDER)
return interpolatePrettyPlaceholder(formattedTitle, normalisedValue);

return util.format(formattedTitle, normalisedValue);
}, interpolateTitleIndex(interpolateEscapedPlaceholders(title), rowIndex))
return util.format(formattedTitle, normalisedValue);
},
interpolateTitleIndex(interpolateEscapedPlaceholders(title), rowIndex),
)
.replace(new RegExp(JEST_EACH_PLACEHOLDER_ESCAPE, 'g'), PLACEHOLDER_PREFIX);

const normalisePlaceholderValue = (value: unknown) =>
Expand Down
4 changes: 3 additions & 1 deletion packages/jest-expect/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import type {
} from 'jest-snapshot';

export type JestExpect = {
<T = unknown>(actual: T): JestMatchers<void, T> &
<T = unknown>(
actual: T,
): JestMatchers<void, T> &
Inverse<JestMatchers<void, T>> &
PromiseMatchers<T>;
// Duplicated due to https://github.com/microsoft/rushstack/issues/1709
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-jasmine2/src/__tests__/reporter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ describe('Jasmine2Reporter', () => {
description: 'description',
failedExpectations: [],
fullName: name,
} as any as SpecResult);
}) as any as SpecResult;
reporter.suiteStarted({description: 'parent'} as SuiteResult);
reporter.suiteStarted({description: 'child'} as SuiteResult);
reporter.specDone(makeSpec('spec 1'));
Expand Down
3 changes: 1 addition & 2 deletions packages/jest-mock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,8 +743,7 @@ export class ModuleMocker {
}

return finalReturnValue;
},
metadata.length || 0);
}, metadata.length || 0);

const f = this._createMockFunction(metadata, mockConstructor) as Mock;
f._isMockFunction = true;
Expand Down
21 changes: 16 additions & 5 deletions packages/jest-types/src/Global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,35 +57,46 @@ export type EachTestFn<EachCallback extends TestCallback> = (

interface Each<EachFn extends TestFn | BlockFn> {
// when the table is an array of object literals
<T extends Record<string, unknown>>(table: ReadonlyArray<T>): (
<T extends Record<string, unknown>>(
table: ReadonlyArray<T>,
): (
name: string | NameLike,
fn: (arg: T, done: DoneFn) => ReturnType<EachFn>,
timeout?: number,
) => void;

// when the table is an array of tuples
<T extends readonly [unknown, ...Array<unknown>]>(table: ReadonlyArray<T>): (
<T extends readonly [unknown, ...Array<unknown>]>(
table: ReadonlyArray<T>,
): (
name: string | NameLike,
fn: (...args: T) => ReturnType<EachFn>,
timeout?: number,
) => void;

// when the table is an array of arrays
<T extends ReadonlyArray<unknown>>(table: ReadonlyArray<T>): (
<T extends ReadonlyArray<unknown>>(
table: ReadonlyArray<T>,
): (
name: string | NameLike,
fn: (...args: T) => ReturnType<EachFn>,
timeout?: number,
) => void;

// when the table is a tuple or array
<T>(table: ReadonlyArray<T>): (
<T>(
table: ReadonlyArray<T>,
): (
name: string | NameLike,
fn: (arg: T, done: DoneFn) => ReturnType<EachFn>,
timeout?: number,
) => void;

// when the table is a template literal
<T = unknown>(strings: TemplateStringsArray, ...expressions: Array<T>): (
<T = unknown>(
strings: TemplateStringsArray,
...expressions: Array<T>
): (
name: string | NameLike,
fn: (arg: Record<string, T>, done: DoneFn) => ReturnType<EachFn>,
timeout?: number,
Expand Down
20 changes: 10 additions & 10 deletions packages/jest-worker/src/base/__tests__/BaseWorkerPool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ describe('BaseWorkerPool', () => {
({
forceExit: jest.fn(),
getStderr: () =>
({once() {}, pipe() {}} as unknown as NodeJS.ReadStream),
({once() {}, pipe() {}}) as unknown as NodeJS.ReadStream,
getStdout: () =>
({once() {}, pipe() {}} as unknown as NodeJS.ReadStream),
({once() {}, pipe() {}}) as unknown as NodeJS.ReadStream,
send: jest.fn(),
waitForExit: () => Promise.resolve(),
} as unknown as WorkerInterface),
}) as unknown as WorkerInterface,
);
});

Expand Down Expand Up @@ -138,15 +138,15 @@ describe('BaseWorkerPool', () => {
pipe(errStream: NodeJS.WritableStream) {
err.push(errStream);
},
} as unknown as NodeJS.ReadableStream),
}) as unknown as NodeJS.ReadableStream,
getStdout: () =>
({
once() {},
pipe(outStream: NodeJS.WritableStream) {
out.push(outStream);
},
} as unknown as NodeJS.ReadableStream),
} as WorkerInterface),
}) as unknown as NodeJS.ReadableStream,
}) as WorkerInterface,
);

const farm = new MockWorkerPool('/tmp/baz.js', {
Expand Down Expand Up @@ -181,7 +181,7 @@ describe('BaseWorkerPool', () => {
getStderr: () => null,
getStdout: () => null,
send: () => null,
} as unknown as WorkerInterface),
}) as unknown as WorkerInterface,
);

const farm = new MockWorkerPool('/tmp/baz.js', {
Expand Down Expand Up @@ -225,7 +225,7 @@ describe('BaseWorkerPool', () => {
getStdout: () => null,
send: jest.fn(),
waitForExit: () => Promise.resolve(),
} as unknown as WorkerInterface),
}) as unknown as WorkerInterface,
);

const pool = new MockWorkerPool('/tmp/baz.js', {
Expand Down Expand Up @@ -253,7 +253,7 @@ describe('BaseWorkerPool', () => {
send: jest.fn(),
waitForExit: () =>
new Promise(resolve => (worker0Exited = resolve)),
} as unknown as WorkerInterface),
}) as unknown as WorkerInterface,
).mockImplementation(
() =>
({
Expand All @@ -262,7 +262,7 @@ describe('BaseWorkerPool', () => {
getStdout: () => null,
send: jest.fn(),
waitForExit: () => Promise.resolve(),
} as unknown as WorkerInterface),
}) as unknown as WorkerInterface,
);

const pool = new MockWorkerPool('/tmp/baz.js', {
Expand Down
20 changes: 12 additions & 8 deletions scripts/build.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import chalk from 'chalk';
import glob from 'glob';
import fs from 'graceful-fs';
import micromatch from 'micromatch';
import prettier from 'prettier';
import * as prettier from 'prettier';
import transformOptions from '../babel.config.js';
import {
OK,
Expand All @@ -42,7 +42,7 @@ const IGNORE_PATTERN = '**/__{tests,mocks}__/**';
const INLINE_REQUIRE_EXCLUDE_LIST =
/packages\/expect|(jest-(circus|diff|get-type|jasmine2|matcher-utils|message-util|regex-util|snapshot))|pretty-format\//;

const prettierConfig = prettier.resolveConfig.sync(
const prettierConfig = await prettier.resolveConfig(
fileURLToPath(import.meta.url),
);
prettierConfig.trailingComma = 'none';
Expand All @@ -60,13 +60,13 @@ function getBuildPath(file, buildFolder) {
return path.resolve(pkgBuildPath, relativeToSrcPath).replace(/\.ts$/, '.js');
}

function buildNodePackage({packageDir, pkg}) {
async function buildNodePackage({packageDir, pkg}) {
const srcDir = path.resolve(packageDir, SRC_DIR);
const files = glob.sync('**/*', {absolute: true, cwd: srcDir, nodir: true});

process.stdout.write(adjustToTerminalWidth(`${pkg.name}\n`));

files.forEach(file => buildFile(file, true));
await Promise.all(files.map(file => buildFile(file)));

assert.ok(
fs.existsSync(path.resolve(packageDir, pkg.main)),
Expand All @@ -76,7 +76,7 @@ function buildNodePackage({packageDir, pkg}) {
process.stdout.write(`${OK}\n`);
}

function buildFile(file, silent) {
async function buildFile(file, silent) {
const destPath = getBuildPath(file, BUILD_DIR);

if (micromatch.isMatch(file, IGNORE_PATTERN)) {
Expand Down Expand Up @@ -131,7 +131,7 @@ function buildFile(file, silent) {
}

const transformed = babel.transformFileSync(file, options).code;
const prettyCode = prettier.format(transformed, prettierConfig);
const prettyCode = await prettier.format(transformed, prettierConfig);

fs.writeFileSync(destPath, prettyCode);

Expand All @@ -150,9 +150,13 @@ function buildFile(file, silent) {
const files = process.argv.slice(2);

if (files.length) {
files.forEach(file => buildFile(file));
for (const file of files) {
await buildFile(file);
}
} else {
const packages = getPackages();
process.stdout.write(chalk.inverse(' Building packages \n'));
packages.forEach(buildNodePackage);
for (const pkg of packages) {
await buildNodePackage(pkg);
}
}
4 changes: 2 additions & 2 deletions scripts/bundleTs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import prettier from 'prettier';
import {rimraf} from 'rimraf';
import {getPackages} from './buildUtils.mjs';

const prettierConfig = prettier.resolveConfig.sync(
const prettierConfig = await prettier.resolveConfig(
fileURLToPath(import.meta.url).replace(/\.js$/, '.d.ts'),
);

Expand Down Expand Up @@ -194,7 +194,7 @@ await Promise.all(
...definitionFile.split(copyrightSnippet),
].join('\n');

const formattedContent = prettier.format(definitionFile, {
const formattedContent = await prettier.format(definitionFile, {
...prettierConfig,
filepath,
});
Expand Down
Loading