Skip to content

Commit e760ec4

Browse files
doniyor2109SimenB
authored andcommitted
jest snapshot - TS migration (#7899)
1 parent d9d501a commit e760ec4

29 files changed

+492
-341
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
- `[babel-jest]`: Migrate to TypeScript ([#7862](https://github.com/facebook/jest/pull/7862))
4040
- `[jest-resolve]`: Migrate to TypeScript ([#7871](https://github.com/facebook/jest/pull/7871))
4141
- `[@jest/reporter]`: New package extracted from `jest-cli` ([#7902](https://github.com/facebook/jest/pull/7902))
42+
- `[jest-snapshot]`: Migrate to TypeScript ([#7899](https://github.com/facebook/jest/pull/7899))
4243

4344
### Performance
4445

packages/jest-message-util/src/index.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ import micromatch from 'micromatch';
1313
import slash from 'slash';
1414
import {codeFrameColumns} from '@babel/code-frame';
1515
import StackUtils from 'stack-utils';
16+
import {Frame} from './types';
17+
18+
export {Frame} from './types';
1619

1720
type Path = Config.Path;
1821
type AssertionResult = TestResult.AssertionResult;
@@ -227,7 +230,7 @@ export const getStackTraceLines = (
227230
options: StackTraceOptions = {noStackTrace: false},
228231
) => removeInternalStackEntries(stack.split(/\n/), options);
229232

230-
export const getTopFrame = (lines: string[]) => {
233+
export const getTopFrame = (lines: string[]): Frame | null => {
231234
for (const line of lines) {
232235
if (line.includes(PATH_NODE_MODULES) || line.includes(PATH_JEST_PACKAGES)) {
233236
continue;
@@ -236,7 +239,7 @@ export const getTopFrame = (lines: string[]) => {
236239
const parsedFrame = stackUtils.parseLine(line.trim());
237240

238241
if (parsedFrame && parsedFrame.file) {
239-
return parsedFrame;
242+
return parsedFrame as Frame;
240243
}
241244
}
242245

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
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 {StackData} from 'stack-utils';
9+
10+
export interface Frame extends StackData {
11+
file: string;
12+
}

packages/jest-snapshot/package.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@
88
},
99
"license": "MIT",
1010
"main": "build/index.js",
11+
"types": "build/index.d.ts",
1112
"dependencies": {
1213
"@babel/types": "^7.0.0",
14+
"@jest/types": "^24.1.0",
1315
"chalk": "^2.0.1",
1416
"jest-diff": "^24.0.0",
1517
"jest-matcher-utils": "^24.0.0",
@@ -20,9 +22,15 @@
2022
"pretty-format": "^24.0.0",
2123
"semver": "^5.5.0"
2224
},
25+
"peerDependencies": {
26+
"jest-haste-map": "^24.0.0"
27+
},
2328
"devDependencies": {
2429
"@types/mkdirp": "^0.5.2",
30+
"@types/natural-compare": "^1.4.0",
31+
"@types/prettier": "^1.16.1",
2532
"@types/semver": "^5.5.0",
33+
"jest-haste-map": "^24.0.0",
2634
"prettier": "^1.13.4"
2735
},
2836
"engines": {

packages/jest-snapshot/src/State.js renamed to packages/jest-snapshot/src/State.ts

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@
33
*
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
6-
*
7-
* @flow
86
*/
97

10-
import type {Path, SnapshotUpdateState} from 'types/Config';
11-
128
import fs from 'fs';
9+
import {Config} from '@jest/types';
10+
1311
import {getTopFrame, getStackTraceLines} from 'jest-message-util';
1412
import {
1513
saveSnapshotFile,
@@ -19,41 +17,44 @@ import {
1917
testNameToKey,
2018
unescape,
2119
} from './utils';
22-
import {saveInlineSnapshots, type InlineSnapshot} from './inline_snapshots';
20+
import {saveInlineSnapshots, InlineSnapshot} from './inline_snapshots';
21+
import {SnapshotData} from './types';
2322

24-
export type SnapshotStateOptions = {|
25-
updateSnapshot: SnapshotUpdateState,
26-
getPrettier: () => null | any,
27-
getBabelTraverse: () => Function,
28-
expand?: boolean,
29-
|};
23+
export type SnapshotStateOptions = {
24+
updateSnapshot: Config.SnapshotUpdateState;
25+
getPrettier: () => null | any;
26+
getBabelTraverse: () => Function;
27+
expand?: boolean;
28+
};
3029

31-
export type SnapshotMatchOptions = {|
32-
testName: string,
33-
received: any,
34-
key?: string,
35-
inlineSnapshot?: string,
36-
error?: Error,
37-
|};
30+
export type SnapshotMatchOptions = {
31+
testName: string;
32+
received: any;
33+
key?: string;
34+
inlineSnapshot?: string;
35+
error?: Error;
36+
};
3837

3938
export default class SnapshotState {
40-
_counters: Map<string, number>;
41-
_dirty: boolean;
42-
_index: number;
43-
_updateSnapshot: SnapshotUpdateState;
44-
_snapshotData: {[key: string]: string};
45-
_snapshotPath: Path;
46-
_inlineSnapshots: Array<InlineSnapshot>;
47-
_uncheckedKeys: Set<string>;
48-
_getBabelTraverse: () => Function;
49-
_getPrettier: () => null | any;
39+
private _counters: Map<string, number>;
40+
private _dirty: boolean;
41+
// @ts-ignore
42+
private _index: number;
43+
private _updateSnapshot: Config.SnapshotUpdateState;
44+
private _snapshotData: SnapshotData;
45+
private _snapshotPath: Config.Path;
46+
private _inlineSnapshots: Array<InlineSnapshot>;
47+
private _uncheckedKeys: Set<string>;
48+
private _getBabelTraverse: () => Function;
49+
private _getPrettier: () => null | any;
50+
5051
added: number;
5152
expand: boolean;
5253
matched: number;
5354
unmatched: number;
5455
updated: number;
5556

56-
constructor(snapshotPath: Path, options: SnapshotStateOptions) {
57+
constructor(snapshotPath: Config.Path, options: SnapshotStateOptions) {
5758
this._snapshotPath = snapshotPath;
5859
const {data, dirty} = getSnapshotData(
5960
this._snapshotPath,
@@ -83,15 +84,15 @@ export default class SnapshotState {
8384
});
8485
}
8586

86-
_addSnapshot(
87+
private _addSnapshot(
8788
key: string,
8889
receivedSerialized: string,
89-
options: {isInline: boolean, error?: Error},
90+
options: {isInline: boolean; error?: Error},
9091
) {
9192
this._dirty = true;
9293
if (options.isInline) {
9394
const error = options.error || new Error();
94-
const lines = getStackTraceLines(error.stack);
95+
const lines = getStackTraceLines(error.stack || '');
9596
const frame = getTopFrame(lines);
9697
if (!frame) {
9798
throw new Error(
@@ -251,7 +252,7 @@ export default class SnapshotState {
251252
}
252253
}
253254

254-
fail(testName: string, received: any, key?: string) {
255+
fail(testName: string, _received: any, key?: string) {
255256
this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
256257
const count = Number(this._counters.get(testName));
257258

packages/jest-snapshot/src/__tests__/inline_snapshots.test.js renamed to packages/jest-snapshot/src/__tests__/inline_snapshots.test.ts

Lines changed: 34 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -3,65 +3,53 @@
33
*
44
* This source code is licensed under the MIT license found in the
55
* LICENSE file in the root directory of this source tree.
6-
*
7-
* @flow
86
*/
97

108
jest.mock('fs');
119
jest.mock('prettier');
1210

13-
const fs = require('fs');
14-
const path = require('path');
15-
const prettier = require('prettier');
16-
const babelTraverse = require('@babel/traverse').default;
11+
import fs from 'fs';
12+
import path from 'path';
13+
import prettier from 'prettier';
14+
import babelTraverse from '@babel/traverse';
15+
import {Frame} from 'jest-message-util';
1716

18-
const {saveInlineSnapshots} = require('../inline_snapshots');
17+
import {saveInlineSnapshots} from '../inline_snapshots';
1918

2019
const writeFileSync = fs.writeFileSync;
2120
const readFileSync = fs.readFileSync;
2221
const existsSync = fs.existsSync;
2322
const statSync = fs.statSync;
2423
const readdirSync = fs.readdirSync;
2524
beforeEach(() => {
26-
// $FlowFixMe mock
2725
fs.writeFileSync = jest.fn();
28-
// $FlowFixMe mock
2926
fs.readFileSync = jest.fn();
30-
// $FlowFixMe mock
3127
fs.existsSync = jest.fn(() => true);
32-
// $FlowFixMe mock
33-
fs.statSync = jest.fn(filePath => ({
28+
(fs.statSync as jest.Mock).mockImplementation(filePath => ({
3429
isDirectory: () => !filePath.endsWith('.js'),
3530
}));
36-
// $FlowFixMe mock
3731
fs.readdirSync = jest.fn(() => []);
3832

39-
prettier.resolveConfig.sync.mockReset();
33+
(prettier.resolveConfig.sync as jest.Mock).mockReset();
4034
});
4135
afterEach(() => {
42-
// $FlowFixMe mock
4336
fs.writeFileSync = writeFileSync;
44-
// $FlowFixMe mock
4537
fs.readFileSync = readFileSync;
46-
// $FlowFixMe mock
4738
fs.existsSync = existsSync;
48-
// $FlowFixMe mock
4939
fs.statSync = statSync;
50-
// $FlowFixMe mock
5140
fs.readdirSync = readdirSync;
5241
});
5342

5443
test('saveInlineSnapshots() replaces empty function call with a template literal', () => {
5544
const filename = path.join(__dirname, 'my.test.js');
56-
// $FlowFixMe mock
57-
fs.readFileSync = (jest.fn(
45+
(fs.readFileSync as jest.Mock).mockImplementation(
5846
() => `expect(1).toMatchInlineSnapshot();\n`,
59-
): any);
47+
);
6048

6149
saveInlineSnapshots(
6250
[
6351
{
64-
frame: {column: 11, file: filename, line: 1},
52+
frame: {column: 11, file: filename, line: 1} as Frame,
6553
snapshot: `1`,
6654
},
6755
],
@@ -79,25 +67,26 @@ test.each([['babylon'], ['flow'], ['typescript']])(
7967
'saveInlineSnapshots() replaces existing template literal - %s parser',
8068
parser => {
8169
const filename = path.join(__dirname, 'my.test.js');
82-
// $FlowFixMe mock
83-
fs.readFileSync = (jest.fn(
70+
(fs.readFileSync as jest.Mock).mockImplementation(
8471
() => 'expect(1).toMatchInlineSnapshot(`2`);\n',
85-
): any);
72+
);
8673

87-
prettier.resolveConfig.sync.mockReturnValue({parser});
74+
(prettier.resolveConfig.sync as jest.Mock).mockReturnValue({parser});
8875

8976
saveInlineSnapshots(
9077
[
9178
{
92-
frame: {column: 11, file: filename, line: 1},
79+
frame: {column: 11, file: filename, line: 1} as Frame,
9380
snapshot: `1`,
9481
},
9582
],
9683
prettier,
9784
babelTraverse,
9885
);
9986

100-
expect(prettier.resolveConfig.sync.mock.results[0].value).toEqual({parser});
87+
expect(
88+
(prettier.resolveConfig.sync as jest.Mock).mock.results[0].value,
89+
).toEqual({parser});
10190

10291
expect(fs.writeFileSync).toHaveBeenCalledWith(
10392
filename,
@@ -108,15 +97,14 @@ test.each([['babylon'], ['flow'], ['typescript']])(
10897

10998
test('saveInlineSnapshots() replaces existing template literal with property matchers', () => {
11099
const filename = path.join(__dirname, 'my.test.js');
111-
// $FlowFixMe mock
112-
fs.readFileSync = (jest.fn(
100+
(fs.readFileSync as jest.Mock).mockImplementation(
113101
() => 'expect(1).toMatchInlineSnapshot({}, `2`);\n',
114-
): any);
102+
);
115103

116104
saveInlineSnapshots(
117105
[
118106
{
119-
frame: {column: 11, file: filename, line: 1},
107+
frame: {column: 11, file: filename, line: 1} as Frame,
120108
snapshot: `1`,
121109
},
122110
],
@@ -132,16 +120,15 @@ test('saveInlineSnapshots() replaces existing template literal with property mat
132120

133121
test('saveInlineSnapshots() throws if frame does not match', () => {
134122
const filename = path.join(__dirname, 'my.test.js');
135-
// $FlowFixMe mock
136-
fs.readFileSync = (jest.fn(
123+
(fs.readFileSync as jest.Mock).mockImplementation(
137124
() => 'expect(1).toMatchInlineSnapshot();\n',
138-
): any);
125+
);
139126

140127
const save = () =>
141128
saveInlineSnapshots(
142129
[
143130
{
144-
frame: {column: 2 /* incorrect */, file: filename, line: 1},
131+
frame: {column: 2 /* incorrect */, file: filename, line: 1} as Frame,
145132
snapshot: `1`,
146133
},
147134
],
@@ -154,12 +141,11 @@ test('saveInlineSnapshots() throws if frame does not match', () => {
154141

155142
test('saveInlineSnapshots() throws if multiple calls to to the same location', () => {
156143
const filename = path.join(__dirname, 'my.test.js');
157-
// $FlowFixMe mock
158-
fs.readFileSync = (jest.fn(
144+
(fs.readFileSync as jest.Mock).mockImplementation(
159145
() => 'expect(1).toMatchInlineSnapshot();\n',
160-
): any);
146+
);
161147

162-
const frame = {column: 11, file: filename, line: 1};
148+
const frame = {column: 11, file: filename, line: 1} as Frame;
163149
const save = () =>
164150
saveInlineSnapshots(
165151
[{frame, snapshot: `1`}, {frame, snapshot: `2`}],
@@ -174,12 +160,11 @@ test('saveInlineSnapshots() throws if multiple calls to to the same location', (
174160

175161
test('saveInlineSnapshots() uses escaped backticks', () => {
176162
const filename = path.join(__dirname, 'my.test.js');
177-
// $FlowFixMe mock
178-
fs.readFileSync = (jest.fn(
163+
(fs.readFileSync as jest.Mock).mockImplementation(
179164
() => 'expect("`").toMatchInlineSnapshot();\n',
180-
): any);
165+
);
181166

182-
const frame = {column: 13, file: filename, line: 1};
167+
const frame = {column: 13, file: filename, line: 1} as Frame;
183168
saveInlineSnapshots([{frame, snapshot: '`'}], prettier, babelTraverse);
184169

185170
expect(fs.writeFileSync).toHaveBeenCalledWith(
@@ -190,19 +175,18 @@ test('saveInlineSnapshots() uses escaped backticks', () => {
190175

191176
test('saveInlineSnapshots() works with non-literals in expect call', () => {
192177
const filename = path.join(__dirname, 'my.test.js');
193-
// $FlowFixMe mock
194-
fs.readFileSync = (jest.fn(
178+
(fs.readFileSync as jest.Mock).mockImplementation(
195179
() => `expect({a: 'a'}).toMatchInlineSnapshot();\n`,
196-
): any);
197-
prettier.resolveConfig.sync.mockReturnValue({
180+
);
181+
(prettier.resolveConfig.sync as jest.Mock).mockReturnValue({
198182
bracketSpacing: false,
199183
singleQuote: true,
200184
});
201185

202186
saveInlineSnapshots(
203187
[
204188
{
205-
frame: {column: 18, file: filename, line: 1},
189+
frame: {column: 18, file: filename, line: 1} as Frame,
206190
snapshot: `{a: 'a'}`,
207191
},
208192
],

0 commit comments

Comments
 (0)