Skip to content

Commit 983274a

Browse files
SimenBeps1lon
andauthored
feat: Let babel find config when updating inline snapshots (#13150)
Co-authored-by: eps1lon <[email protected]>
1 parent d2ff18a commit 983274a

File tree

8 files changed

+157
-8
lines changed

8 files changed

+157
-8
lines changed

CHANGELOG.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
- `[@jest/globals]` Add `jest.Mocked`, `jest.MockedClass`, `jest.MockedFunction` and `jest.MockedObject` utility types ([#12727](https://github.com/facebook/jest/pull/12727))
1010
- `[jest-mock]` [**BREAKING**] Refactor `Mocked*` utility types. `MaybeMockedDeep` and `MaybeMocked` became `Mocked` and `MockedShallow` respectively; only deep mocked variants of `MockedClass`, `MockedFunction` and `MockedObject` are exported ([#13123](https://github.com/facebook/jest/pull/13123), [#13124](https://github.com/facebook/jest/pull/13124))
1111
- `[jest-mock]` [**BREAKING**] Change the default `jest.mocked` helper’s behavior to deep mocked ([#13125](https://github.com/facebook/jest/pull/13125))
12-
- `[jest-worker]` Adds `workerIdleMemoryLimit` option which is used as a check for worker memory leaks >= Node 16.11.0 and recycles child workers as required. ([#13056](https://github.com/facebook/jest/pull/13056), [#13105](https://github.com/facebook/jest/pull/13105), [#13106](https://github.com/facebook/jest/pull/13106), [#13107](https://github.com/facebook/jest/pull/13107))
12+
- `[jest-snapshot]` [**BREAKING**] Let `babel` find config when updating inline snapshots ([#13150](https://github.com/facebook/jest/pull/13150))
13+
- `[jest-worker]` Adds `workerIdleMemoryLimit` option which is used as a check for worker memory leaks >= Node 16.11.0 and recycles child workers as required ([#13056](https://github.com/facebook/jest/pull/13056), [#13105](https://github.com/facebook/jest/pull/13105), [#13106](https://github.com/facebook/jest/pull/13106), [#13107](https://github.com/facebook/jest/pull/13107))
1314
- `[pretty-format]` [**BREAKING**] Remove `ConvertAnsi` plugin in favour of `jest-serializer-ansi-escapes` ([#13040](https://github.com/facebook/jest/pull/13040))
1415

1516
### Fixes
@@ -26,6 +27,7 @@
2627
- `[docs]` Fix webpack name ([#13049](https://github.com/facebook/jest/pull/13049))
2728
- `[docs]` Explicit how to set `n` for `--bail` ([#13128](https://github.com/facebook/jest/pull/13128))
2829
- `[jest-leak-detector]` Remove support for `weak-napi` ([#13035](https://github.com/facebook/jest/pull/13035))
30+
- `[jest-snapshot]` [**BREAKING**] Require `rootDir` as argument to `SnapshotState` ([#13150](https://github.com/facebook/jest/pull/13150))
2931

3032
### Performance
3133

e2e/Utils.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,11 @@ export const runYarnInstall = (cwd: string, env?: Record<string, string>) => {
5454
fs.writeFileSync(lockfilePath, '');
5555
}
5656

57-
return run(exists ? 'yarn install --immutable' : 'yarn install', cwd, env);
57+
return run(
58+
exists ? 'yarn install --immutable' : 'yarn install --no-immutable',
59+
cwd,
60+
env,
61+
);
5862
};
5963

6064
export const linkJestPackage = (packageName: string, cwd: string) => {
@@ -168,7 +172,7 @@ export const sortLines = (output: string) =>
168172
.map(str => str.trim())
169173
.join('\n');
170174

171-
interface JestPackageJson extends PackageJson {
175+
export interface JestPackageJson extends PackageJson {
172176
jest: Config.InitialOptions;
173177
}
174178

@@ -180,7 +184,7 @@ const DEFAULT_PACKAGE_JSON: JestPackageJson = {
180184

181185
export const createEmptyPackage = (
182186
directory: string,
183-
packageJson: PackageJson = DEFAULT_PACKAGE_JSON,
187+
packageJson: JestPackageJson = DEFAULT_PACKAGE_JSON,
184188
) => {
185189
const packageJsonWithDefaults = {
186190
...packageJson,
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
import {tmpdir} from 'os';
9+
import * as path from 'path';
10+
import {
11+
JestPackageJson,
12+
cleanup,
13+
createEmptyPackage,
14+
runYarnInstall,
15+
writeFiles,
16+
} from '../Utils';
17+
import runJest, {json as runWithJson} from '../runJest';
18+
19+
const DIR = path.resolve(tmpdir(), 'to-match-inline-snapshot-with-jsx');
20+
21+
const babelConfig = {
22+
presets: [
23+
['@babel/preset-env', {targets: {node: 'current'}}],
24+
'@babel/preset-react',
25+
],
26+
};
27+
28+
const pkg: JestPackageJson = {
29+
dependencies: {
30+
react: '^17.0.0',
31+
},
32+
devDependencies: {
33+
'@babel/core': '^7.14.4',
34+
'@babel/preset-env': '^7.14.4',
35+
'@babel/preset-react': '^7.13.13',
36+
'react-test-renderer': '^17.0.2',
37+
},
38+
jest: {
39+
testEnvironment: 'jsdom',
40+
},
41+
};
42+
43+
beforeEach(() => {
44+
cleanup(DIR);
45+
46+
createEmptyPackage(DIR, pkg);
47+
48+
writeFiles(DIR, {
49+
'__tests__/MismatchingSnapshot.test.js': `
50+
import React from 'react';
51+
import renderer from 'react-test-renderer';
52+
53+
test('<div>x</div>', () => {
54+
expect(renderer.create(<div>x</div>).toJSON()).toMatchInlineSnapshot(\`
55+
<div>
56+
y
57+
</div>
58+
\`);
59+
});`,
60+
});
61+
62+
runYarnInstall(DIR, {
63+
YARN_ENABLE_GLOBAL_CACHE: 'true',
64+
YARN_NODE_LINKER: 'node-modules',
65+
});
66+
});
67+
68+
afterAll(() => {
69+
cleanup(DIR);
70+
});
71+
72+
it('successfully runs the tests with external babel config', () => {
73+
writeFiles(DIR, {
74+
'babel.config.js': `module.exports = ${JSON.stringify(babelConfig)};`,
75+
});
76+
77+
const normalRun = runWithJson(DIR, []);
78+
expect(normalRun.exitCode).toBe(1);
79+
expect(normalRun.stderr).toContain('1 snapshot failed from 1 test suite.');
80+
expect(normalRun.json.testResults[0].message).toMatchInlineSnapshot(`
81+
" ● <div>x</div>
82+
83+
expect(received).toMatchInlineSnapshot(snapshot)
84+
85+
Snapshot name: \`<div>x</div> 1\`
86+
87+
- Snapshot - 1
88+
+ Received + 1
89+
90+
<div>
91+
- y
92+
+ x
93+
</div>
94+
95+
3 |
96+
4 | test('<div>x</div>', () => {
97+
> 5 | expect(renderer.create(<div>x</div>).toJSON()).toMatchInlineSnapshot(\`
98+
| ^
99+
6 | <div>
100+
7 | y
101+
8 | </div>
102+
103+
at Object.toMatchInlineSnapshot (__tests__/MismatchingSnapshot.test.js:5:50)
104+
"
105+
`);
106+
107+
const updateSnapshotRun = runJest(DIR, ['--updateSnapshot']);
108+
109+
expect(updateSnapshotRun.exitCode).toBe(0);
110+
expect(updateSnapshotRun.stderr).toContain('1 snapshot updated.');
111+
});

packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapterInit.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ export const initialize = async ({
114114
const snapshotState = new SnapshotState(snapshotPath, {
115115
expand: globalConfig.expand,
116116
prettierPath: config.prettierPath,
117+
rootDir: config.rootDir,
117118
snapshotFormat: config.snapshotFormat,
118119
updateSnapshot: globalConfig.updateSnapshot,
119120
});

packages/jest-jasmine2/src/setup_jest_globals.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,12 +104,13 @@ export default async function setupJestGlobals({
104104

105105
patchJasmine();
106106
const {expand, updateSnapshot} = globalConfig;
107-
const {prettierPath, snapshotFormat} = config;
107+
const {prettierPath, rootDir, snapshotFormat} = config;
108108
const snapshotResolver = await buildSnapshotResolver(config, localRequire);
109109
const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
110110
const snapshotState = new SnapshotState(snapshotPath, {
111111
expand,
112112
prettierPath,
113+
rootDir,
113114
snapshotFormat,
114115
updateSnapshot,
115116
});

packages/jest-snapshot/src/InlineSnapshots.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ export type InlineSnapshot = {
4646

4747
export function saveInlineSnapshots(
4848
snapshots: Array<InlineSnapshot>,
49+
rootDir: string,
4950
prettierPath: string | null,
5051
): void {
5152
let prettier: Prettier | null = null;
@@ -64,6 +65,7 @@ export function saveInlineSnapshots(
6465
saveSnapshotsForFile(
6566
snapshotsByFile[sourceFilePath],
6667
sourceFilePath,
68+
rootDir,
6769
prettier && semver.gte(prettier.version, '1.5.0') ? prettier : undefined,
6870
);
6971
}
@@ -72,6 +74,7 @@ export function saveInlineSnapshots(
7274
const saveSnapshotsForFile = (
7375
snapshots: Array<InlineSnapshot>,
7476
sourceFilePath: string,
77+
rootDir: string,
7578
prettier: Prettier | undefined,
7679
) => {
7780
const sourceFile = fs.readFileSync(sourceFilePath, 'utf8');
@@ -96,7 +99,7 @@ const saveSnapshotsForFile = (
9699
filename: sourceFilePath,
97100
plugins,
98101
presets,
99-
root: path.dirname(sourceFilePath),
102+
root: rootDir,
100103
});
101104
if (!ast) {
102105
throw new Error(`jest-snapshot: Failed to parse ${sourceFilePath}`);

packages/jest-snapshot/src/State.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ export type SnapshotStateOptions = {
2727
prettierPath?: string | null;
2828
expand?: boolean;
2929
snapshotFormat: PrettyFormatOptions;
30+
rootDir: string;
3031
};
3132

3233
export type SnapshotMatchOptions = {
@@ -64,6 +65,7 @@ export default class SnapshotState {
6465
private _uncheckedKeys: Set<string>;
6566
private _prettierPath: string | null;
6667
private _snapshotFormat: PrettyFormatOptions;
68+
private _rootDir: string;
6769

6870
added: number;
6971
expand: boolean;
@@ -92,6 +94,7 @@ export default class SnapshotState {
9294
this._updateSnapshot = options.updateSnapshot;
9395
this.updated = 0;
9496
this._snapshotFormat = options.snapshotFormat;
97+
this._rootDir = options.rootDir;
9598
}
9699

97100
markSnapshotsAsCheckedForTest(testName: string): void {
@@ -154,7 +157,11 @@ export default class SnapshotState {
154157
saveSnapshotFile(this._snapshotData, this._snapshotPath);
155158
}
156159
if (hasInlineSnapshots) {
157-
saveInlineSnapshots(this._inlineSnapshots, this._prettierPath);
160+
saveInlineSnapshots(
161+
this._inlineSnapshots,
162+
this._rootDir,
163+
this._prettierPath,
164+
);
158165
}
159166
status.saved = true;
160167
} else if (!hasExternalSnapshots && fs.existsSync(this._snapshotPath)) {

0 commit comments

Comments
 (0)