Skip to content

Commit

Permalink
fix: prioritize parser used in the project (#13323)
Browse files Browse the repository at this point in the history
  • Loading branch information
JVBorges committed Sep 28, 2022
1 parent e341e46 commit 0c15eb6
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -16,6 +16,7 @@
- `[jest-haste-map]` Remove `__proto__` usage ([#13256](https://github.com/facebook/jest/pull/13256))
- `[jest-mock]` Improve `spyOn` typings to handle optional properties ([#13247](https://github.com/facebook/jest/pull/13247))
- `[jest-snapshot]` Throw useful error when an array is passed as property matchers ([#13263](https://github.com/facebook/jest/pull/13263))
- `[jest-snapshot]` Prioritize parser used in the project ([#13323](https://github.com/facebook/jest/pull/13323))

### Chore & Maintenance

Expand Down
9 changes: 5 additions & 4 deletions packages/jest-snapshot/src/InlineSnapshots.ts
Expand Up @@ -297,14 +297,15 @@ const runPrettier = (
? prettier.resolveConfig.sync(sourceFilePath, {editorconfig: true})
: null;

// Detect the parser for the test file.
// Prioritize parser found in the project config.
// If not found detect the parser for the test file.
// For older versions of Prettier, fallback to a simple parser detection.
// @ts-expect-error - `inferredParser` is `string`
const inferredParser: PrettierParserName | null | undefined =
prettier.getFileInfo
(config && typeof config.parser === 'string' && config.parser) ||
(prettier.getFileInfo
? prettier.getFileInfo.sync(sourceFilePath).inferredParser
: (config && typeof config.parser === 'string' && config.parser) ||
simpleDetectParser(sourceFilePath);
: simpleDetectParser(sourceFilePath));

if (!inferredParser) {
throw new Error(
Expand Down
40 changes: 40 additions & 0 deletions packages/jest-snapshot/src/__tests__/InlineSnapshots.test.ts
Expand Up @@ -689,3 +689,43 @@ test('saveInlineSnapshots() indents awaited snapshots with spaces', () => {
'});\n',
);
});

test('saveInlineSnapshots() prioritize parser from project/editor configuration', () => {
const filename = path.join(dir, 'my.test.js');
fs.writeFileSync(
filename,
'const foo = {\n' +
' "1": "Some value",\n' +
'};\n' +
'test("something", () => {\n' +
' expect("a").toMatchInlineSnapshot();\n' +
'});\n',
);

jest.mocked(prettier.resolveConfig.sync).mockReturnValue({
parser: 'flow',
});

const prettierSpy = jest.spyOn(prettier.getFileInfo, 'sync');

saveInlineSnapshots(
[
{
frame: {column: 15, file: filename, line: 5} as Frame,
snapshot: 'a',
},
],
dir,
'prettier',
);

expect(prettierSpy).not.toBeCalled();
expect(fs.readFileSync(filename, 'utf-8')).toBe(
'const foo = {\n' +
' "1": "Some value",\n' +
'};\n' +
'test("something", () => {\n' +
' expect("a").toMatchInlineSnapshot(`a`);\n' +
'});\n',
);
});

0 comments on commit 0c15eb6

Please sign in to comment.