Skip to content

Commit

Permalink
feat: Let babel find config when updating inline snapshots (#13150)
Browse files Browse the repository at this point in the history
Co-authored-by: eps1lon <[email protected]>
  • Loading branch information
SimenB and eps1lon authored Aug 19, 2022
1 parent d2ff18a commit 983274a
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 8 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
- `[@jest/globals]` Add `jest.Mocked`, `jest.MockedClass`, `jest.MockedFunction` and `jest.MockedObject` utility types ([#12727](https://github.com/facebook/jest/pull/12727))
- `[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))
- `[jest-mock]` [**BREAKING**] Change the default `jest.mocked` helper’s behavior to deep mocked ([#13125](https://github.com/facebook/jest/pull/13125))
- `[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))
- `[jest-snapshot]` [**BREAKING**] Let `babel` find config when updating inline snapshots ([#13150](https://github.com/facebook/jest/pull/13150))
- `[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))
- `[pretty-format]` [**BREAKING**] Remove `ConvertAnsi` plugin in favour of `jest-serializer-ansi-escapes` ([#13040](https://github.com/facebook/jest/pull/13040))

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

### Performance

Expand Down
10 changes: 7 additions & 3 deletions e2e/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ export const runYarnInstall = (cwd: string, env?: Record<string, string>) => {
fs.writeFileSync(lockfilePath, '');
}

return run(exists ? 'yarn install --immutable' : 'yarn install', cwd, env);
return run(
exists ? 'yarn install --immutable' : 'yarn install --no-immutable',
cwd,
env,
);
};

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

interface JestPackageJson extends PackageJson {
export interface JestPackageJson extends PackageJson {
jest: Config.InitialOptions;
}

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

export const createEmptyPackage = (
directory: string,
packageJson: PackageJson = DEFAULT_PACKAGE_JSON,
packageJson: JestPackageJson = DEFAULT_PACKAGE_JSON,
) => {
const packageJsonWithDefaults = {
...packageJson,
Expand Down
111 changes: 111 additions & 0 deletions e2e/__tests__/toMatchInlineSnapshotWithJSX.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {tmpdir} from 'os';
import * as path from 'path';
import {
JestPackageJson,
cleanup,
createEmptyPackage,
runYarnInstall,
writeFiles,
} from '../Utils';
import runJest, {json as runWithJson} from '../runJest';

const DIR = path.resolve(tmpdir(), 'to-match-inline-snapshot-with-jsx');

const babelConfig = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-react',
],
};

const pkg: JestPackageJson = {
dependencies: {
react: '^17.0.0',
},
devDependencies: {
'@babel/core': '^7.14.4',
'@babel/preset-env': '^7.14.4',
'@babel/preset-react': '^7.13.13',
'react-test-renderer': '^17.0.2',
},
jest: {
testEnvironment: 'jsdom',
},
};

beforeEach(() => {
cleanup(DIR);

createEmptyPackage(DIR, pkg);

writeFiles(DIR, {
'__tests__/MismatchingSnapshot.test.js': `
import React from 'react';
import renderer from 'react-test-renderer';
test('<div>x</div>', () => {
expect(renderer.create(<div>x</div>).toJSON()).toMatchInlineSnapshot(\`
<div>
y
</div>
\`);
});`,
});

runYarnInstall(DIR, {
YARN_ENABLE_GLOBAL_CACHE: 'true',
YARN_NODE_LINKER: 'node-modules',
});
});

afterAll(() => {
cleanup(DIR);
});

it('successfully runs the tests with external babel config', () => {
writeFiles(DIR, {
'babel.config.js': `module.exports = ${JSON.stringify(babelConfig)};`,
});

const normalRun = runWithJson(DIR, []);
expect(normalRun.exitCode).toBe(1);
expect(normalRun.stderr).toContain('1 snapshot failed from 1 test suite.');
expect(normalRun.json.testResults[0].message).toMatchInlineSnapshot(`
" ● <div>x</div>
expect(received).toMatchInlineSnapshot(snapshot)
Snapshot name: \`<div>x</div> 1\`
- Snapshot - 1
+ Received + 1
<div>
- y
+ x
</div>
3 |
4 | test('<div>x</div>', () => {
> 5 | expect(renderer.create(<div>x</div>).toJSON()).toMatchInlineSnapshot(\`
| ^
6 | <div>
7 | y
8 | </div>
at Object.toMatchInlineSnapshot (__tests__/MismatchingSnapshot.test.js:5:50)
"
`);

const updateSnapshotRun = runJest(DIR, ['--updateSnapshot']);

expect(updateSnapshotRun.exitCode).toBe(0);
expect(updateSnapshotRun.stderr).toContain('1 snapshot updated.');
});
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ export const initialize = async ({
const snapshotState = new SnapshotState(snapshotPath, {
expand: globalConfig.expand,
prettierPath: config.prettierPath,
rootDir: config.rootDir,
snapshotFormat: config.snapshotFormat,
updateSnapshot: globalConfig.updateSnapshot,
});
Expand Down
3 changes: 2 additions & 1 deletion packages/jest-jasmine2/src/setup_jest_globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,13 @@ export default async function setupJestGlobals({

patchJasmine();
const {expand, updateSnapshot} = globalConfig;
const {prettierPath, snapshotFormat} = config;
const {prettierPath, rootDir, snapshotFormat} = config;
const snapshotResolver = await buildSnapshotResolver(config, localRequire);
const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
const snapshotState = new SnapshotState(snapshotPath, {
expand,
prettierPath,
rootDir,
snapshotFormat,
updateSnapshot,
});
Expand Down
5 changes: 4 additions & 1 deletion packages/jest-snapshot/src/InlineSnapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export type InlineSnapshot = {

export function saveInlineSnapshots(
snapshots: Array<InlineSnapshot>,
rootDir: string,
prettierPath: string | null,
): void {
let prettier: Prettier | null = null;
Expand All @@ -64,6 +65,7 @@ export function saveInlineSnapshots(
saveSnapshotsForFile(
snapshotsByFile[sourceFilePath],
sourceFilePath,
rootDir,
prettier && semver.gte(prettier.version, '1.5.0') ? prettier : undefined,
);
}
Expand All @@ -72,6 +74,7 @@ export function saveInlineSnapshots(
const saveSnapshotsForFile = (
snapshots: Array<InlineSnapshot>,
sourceFilePath: string,
rootDir: string,
prettier: Prettier | undefined,
) => {
const sourceFile = fs.readFileSync(sourceFilePath, 'utf8');
Expand All @@ -96,7 +99,7 @@ const saveSnapshotsForFile = (
filename: sourceFilePath,
plugins,
presets,
root: path.dirname(sourceFilePath),
root: rootDir,
});
if (!ast) {
throw new Error(`jest-snapshot: Failed to parse ${sourceFilePath}`);
Expand Down
9 changes: 8 additions & 1 deletion packages/jest-snapshot/src/State.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export type SnapshotStateOptions = {
prettierPath?: string | null;
expand?: boolean;
snapshotFormat: PrettyFormatOptions;
rootDir: string;
};

export type SnapshotMatchOptions = {
Expand Down Expand Up @@ -64,6 +65,7 @@ export default class SnapshotState {
private _uncheckedKeys: Set<string>;
private _prettierPath: string | null;
private _snapshotFormat: PrettyFormatOptions;
private _rootDir: string;

added: number;
expand: boolean;
Expand Down Expand Up @@ -92,6 +94,7 @@ export default class SnapshotState {
this._updateSnapshot = options.updateSnapshot;
this.updated = 0;
this._snapshotFormat = options.snapshotFormat;
this._rootDir = options.rootDir;
}

markSnapshotsAsCheckedForTest(testName: string): void {
Expand Down Expand Up @@ -154,7 +157,11 @@ export default class SnapshotState {
saveSnapshotFile(this._snapshotData, this._snapshotPath);
}
if (hasInlineSnapshots) {
saveInlineSnapshots(this._inlineSnapshots, this._prettierPath);
saveInlineSnapshots(
this._inlineSnapshots,
this._rootDir,
this._prettierPath,
);
}
status.saved = true;
} else if (!hasExternalSnapshots && fs.existsSync(this._snapshotPath)) {
Expand Down
Loading

0 comments on commit 983274a

Please sign in to comment.