Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
liuxingbaoyu committed Sep 24, 2023
1 parent c922901 commit 911dca2
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 56 deletions.
18 changes: 8 additions & 10 deletions e2e/__tests__/toMatchInlineSnapshotWithPretttier3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ afterAll(() => {
cleanup(JEST_CONFIG_PATH);
});

test('throws correct error', () => {
test('supports passing `null` as `prettierPath`', () => {
writeFiles(DIR, {
'jest.config.js': `
module.exports = {prettierPath: require.resolve('prettier')};
module.exports = {prettierPath: null};
`,
});
writeFiles(TESTS_DIR, {
Expand All @@ -42,16 +42,14 @@ test('throws correct error', () => {
`,
});
const {stderr, exitCode} = runJest(DIR, ['--ci=false']);
expect(stderr).toContain(
'Jest: Inline Snapshots are not supported when using Prettier 3.0.0 or above.',
);
expect(exitCode).toBe(1);
expect(stderr).toContain('Snapshots: 1 written, 1 total');
expect(exitCode).toBe(0);
});

test('supports passing `null` as `prettierPath`', () => {
test('supports passing `prettier-2` as `prettierPath`', () => {
writeFiles(DIR, {
'jest.config.js': `
module.exports = {prettierPath: null};
module.exports = {prettierPath: require.resolve('prettier-2')};
`,
});
writeFiles(TESTS_DIR, {
Expand All @@ -66,10 +64,10 @@ test('supports passing `null` as `prettierPath`', () => {
expect(exitCode).toBe(0);
});

test('supports passing `prettier-2` as `prettierPath`', () => {
test('supports passing `prettier` as `prettierPath`', () => {
writeFiles(DIR, {
'jest.config.js': `
module.exports = {prettierPath: require.resolve('prettier-2')};
module.exports = {prettierPath: require.resolve('prettier')};
`,
});
writeFiles(TESTS_DIR, {
Expand Down
4 changes: 3 additions & 1 deletion packages/jest-snapshot/src/InlineSnapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ export function saveInlineSnapshots(
cachedPrettier.set(`module|${prettierPath}`, prettier);

if (semver.gte(prettier.version, '3.0.0')) {
workerFn = createSyncFn(require.resolve('./worker'));
workerFn = createSyncFn(
require.resolve(/*webpackIgnore: true*/ './worker'),
);
cachedPrettier.set(`worker|${prettierPath}`, workerFn);
}
} catch (error) {
Expand Down
10 changes: 1 addition & 9 deletions packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,7 @@ jest.mock('prettier', () => {
const realPrettier =
jest.requireActual<typeof import('prettier-v2')>('prettier-v2');
const mockPrettier = {
format: (text, opts) =>
realPrettier.format(text, {
pluginSearchDirs: [
(require('path') as typeof import('path')).dirname(
require.resolve('prettier-v2'),
),
],
...opts,
}),
format: (text, opts) => realPrettier.format(text, opts),
getFileInfo: {
sync: () => ({ignored: false, inferredParser: 'babel'}),
} as unknown as typeof prettier.getFileInfo,
Expand Down
31 changes: 21 additions & 10 deletions packages/jest-snapshot/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@

import * as path from 'path';
import type {ParseResult, PluginItem} from '@babel/core';
import type {File, Node, Program, TraversalAncestors} from '@babel/types';
import type {
File,
Node,
Program,
TemplateLiteral,
TraversalAncestors,
} from '@babel/types';
import chalk = require('chalk');
import * as fs from 'graceful-fs';
import naturalCompare = require('natural-compare');
Expand Down Expand Up @@ -422,6 +428,7 @@ export const processPrettierAst = (
ast: File,
options: Record<string, any>,
snapshotMatcherNames: Array<string>,
keepNode?: boolean,
): void => {
traverse(ast, (node: Node, ancestors: TraversalAncestors) => {
if (node.type !== 'CallExpression') return;
Expand Down Expand Up @@ -468,15 +475,19 @@ export const processPrettierAst = (
useSpaces ? ' '.repeat(options.tabWidth ?? 1) : '\t',
);

const replacementNode = templateLiteral(
[
templateElement({
raw: snapshot,
}),
],
[],
);
args[snapshotIndex!] = replacementNode;
if (keepNode) {
(args[snapshotIndex!] as TemplateLiteral).quasis[0].value.raw = snapshot;
} else {
const replacementNode = templateLiteral(
[
templateElement({
raw: snapshot,
}),
],
[],
);
args[snapshotIndex!] = replacementNode;
}
});
};

Expand Down
50 changes: 24 additions & 26 deletions packages/jest-snapshot/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ runAsWorker(
sourceFileWithSnapshots: string,
snapshotMatcherNames: Array<string>,
) => {
prettier ??= await import(prettierPath);
// @ts-expect-error requireOutside
prettier ??= requireOutside(/*webpackIgnore: true*/ prettierPath);

const config = await prettier.resolveConfig(filepath, {editorconfig: true});
const config = await prettier.resolveConfig(filepath, {
editorconfig: true,
});

const inferredParser: string | null =
(typeof config?.parser === 'string' && config.parser) ||
Expand All @@ -22,37 +25,32 @@ runAsWorker(
throw new Error(`Could not infer Prettier parser for file ${filepath}`);
}

sourceFileWithSnapshots = await prettier.format(sourceFileWithSnapshots, {
...config,
filepath,
parser: inferredParser,
});

// @ts-expect-error private API
const {ast} = await prettier.__debug.parse(sourceFileWithSnapshots, {
...config,
filepath,
originalText: sourceFileWithSnapshots,
parser: inferredParser,
});
processPrettierAst(ast, config!, snapshotMatcherNames, true);
// Snapshots have now been inserted. Run prettier to make sure that the code is
// formatted, except snapshot indentation. Snapshots cannot be formatted until
// after the initial format because we don't know where the call expression
// will be placed (specifically its indentation), so we have to do two
// prettier.format calls back-to-back.
return await prettier.format(
await prettier.format(sourceFileWithSnapshots, {
...config,
filepath,
parser: inferredParser,
}),
{
return /** @ts-expect-error private API */ (
await prettier.__debug.formatAST(ast, {
...config,
filepath,
originalText: sourceFileWithSnapshots,
parser: inferredParser,
plugins: [
{
printers: {
'jest-snapshot-plugin': {
preprocess(ast, options) {
processPrettierAst(ast, options, snapshotMatcherNames);
return ast;
},
print(path, options, print) {
return print(path);
},
},
},
},
],
},
);
})
).formatted;
},
);
2 changes: 2 additions & 0 deletions scripts/buildUtils.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,8 @@ export function createWebpackConfigs() {
}
: pkg.name === 'jest-repl'
? {repl: path.resolve(packageDir, './src/cli/repl.ts')}
: pkg.name === 'jest-snapshot'
? {worker: path.resolve(packageDir, './src/worker.ts')}
: {};

const extraEntryPoints =
Expand Down

0 comments on commit 911dca2

Please sign in to comment.