Skip to content

Commit 9126abd

Browse files
authored
upgrade jest-snapshot to v30 and cleanup types (#117)
1 parent a03bf1c commit 9126abd

File tree

9 files changed

+622
-459
lines changed

9 files changed

+622
-459
lines changed

package.json

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "jest-editor-support",
3-
"version": "32.0.0-beta.0",
3+
"version": "32.0.0-beta.1",
44
"repository": {
55
"type": "git",
66
"url": "https://github.com/jest-community/jest-editor-support"
@@ -10,7 +10,7 @@
1010
"scripts": {
1111
"clean": "rimraf ./build ./index.d.ts",
1212
"build": "tsc --noEmit",
13-
"build:types": "dts-bundle-generator -o ./index.d.ts src/index.ts",
13+
"build:types": "dts-bundle-generator -o ./index.d.ts src/index.ts --project ./tsconfig.types.json",
1414
"build:prod": "yarn clean & tsc -p tsconfig.prod.json",
1515
"prepublish": "yarn build:prod && yarn build:types",
1616
"test": "jest",
@@ -24,10 +24,10 @@
2424
"devDependencies": {
2525
"@babel/core": "^7.20.12",
2626
"@types/jest": "^29.2.4",
27-
"@types/node": "^18.11.16",
27+
"@types/node": "^20.12.7",
2828
"@typescript-eslint/eslint-plugin": "^5.46.1",
2929
"@typescript-eslint/parser": "^5.46.1",
30-
"dts-bundle-generator": "^9.3.1",
30+
"dts-bundle-generator": "^9.5.1",
3131
"eslint": "^8.57.0",
3232
"eslint-config-prettier": "^9.1.0",
3333
"eslint-plugin-jest": "^27.9.0",
@@ -42,9 +42,10 @@
4242
"@babel/parser": "^7.20.7",
4343
"@babel/traverse": "7.23.2",
4444
"@babel/types": "^7.20.7",
45+
"@jest/snapshot-utils": "^30.0.0-alpha.5",
4546
"@jest/test-result": "^29.3.1",
4647
"@jest/types": "^29.3.1",
47-
"jest-snapshot": "^27.2.0"
48+
"jest-snapshot": "^30.0.0-alpha.5"
4849
},
4950
"jest": {
5051
"preset": "ts-jest",

src/Runner.ts

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,35 +15,47 @@ import type {Options, MessageType} from './types';
1515
import ProjectWorkspace from './project_workspace';
1616
import {createProcess} from './Process';
1717

18-
export type RunnerEvent =
19-
| 'processClose'
20-
| 'processExit'
21-
| 'executableJSON'
22-
| 'executableStdErr'
23-
| 'executableOutput'
24-
| 'terminalError';
18+
export type RunnerEventMap = {
19+
processClose: [code: number | null, signal: string | null];
20+
processExit: [code: number | null, signal: string | null];
21+
executableJSON: [data: object, {noTestsFound: boolean}];
22+
executableStdErr: [data: Buffer, {type: MessageType}];
23+
executableOutput: [data: string];
24+
terminalError: [error: string];
25+
debuggerProcessExit: [];
26+
};
27+
28+
export type AllRunnerEvent = keyof RunnerEventMap;
29+
export type RunnerEvent = Exclude<AllRunnerEvent, 'debuggerProcessExit'>;
2530

2631
// This class represents the running process, and
2732
// passes out events when it understands what data is being
2833
// pass sent out of the process
29-
export default class Runner extends EventEmitter {
34+
export default class Runner extends EventEmitter<RunnerEventMap> {
35+
/** @internal */
3036
runProcess?: ChildProcess;
3137

38+
/** @internal */
3239
outputPath: string;
3340

41+
/** @internal */
3442
workspace: ProjectWorkspace;
3543

36-
_createProcess: (workspace: ProjectWorkspace, args: string[]) => ChildProcess;
44+
/** @internal */
45+
private _createProcess: (workspace: ProjectWorkspace, args: string[]) => ChildProcess;
3746

3847
watchMode = false;
3948

4049
watchAll = false;
4150

51+
/** @internal */
4252
options: Options;
4353

54+
/** @internal */
4455
prevMessageTypes: MessageType[];
4556

46-
_exited: boolean;
57+
/** @internal */
58+
private _exited: boolean;
4759

4860
constructor(workspace: ProjectWorkspace, options?: Options) {
4961
super();
@@ -56,7 +68,8 @@ export default class Runner extends EventEmitter {
5668
this._exited = false;
5769
}
5870

59-
__convertDashedArgs(args: string[]): string[] {
71+
/** @internal */
72+
private __convertDashedArgs(args: string[]): string[] {
6073
if (!this.workspace.useDashedArgs) {
6174
return args;
6275
}
@@ -66,7 +79,8 @@ export default class Runner extends EventEmitter {
6679
);
6780
}
6881

69-
_getArgs(): string[] {
82+
/** @internal */
83+
private _getArgs(): string[] {
7084
if (this.options.args && this.options.args.replace) {
7185
return this.options.args.skipConversion
7286
? this.options.args.args
@@ -153,6 +167,7 @@ export default class Runner extends EventEmitter {
153167
}
154168

155169
/**
170+
* @internal
156171
* parse the stdin/out stream buffer for recognized messages.
157172
*
158173
* note: if these messages coming in in separate chucks, we might not be able to
@@ -165,7 +180,7 @@ export default class Runner extends EventEmitter {
165180
* @returns {MessageType}
166181
* @memberof Runner
167182
*/
168-
_parseOutput(data: Buffer, isStdErr: boolean): MessageType {
183+
private _parseOutput(data: Buffer, isStdErr: boolean): MessageType {
169184
const msgType = this.findMessageType(data);
170185
switch (msgType) {
171186
case MessageTypes.testResults:
@@ -248,7 +263,7 @@ export default class Runner extends EventEmitter {
248263
this.runProcess = undefined;
249264
}
250265

251-
// eslint-disable-next-line class-methods-use-this
266+
/** @internal */
252267
findMessageType(buf: Buffer): MessageType {
253268
const noTestRegex = /No tests found related to files changed since ((last commit)|("[a-z0-9]+"))./;
254269
const watchUsageRegex = /^\s*Watch Usage\b/;
@@ -265,6 +280,7 @@ export default class Runner extends EventEmitter {
265280
return match ? match.messageType : MessageTypes.unknown;
266281
}
267282

283+
/** @internal */
268284
doResultsFollowNoTestsFoundMessage(): boolean {
269285
if (this.prevMessageTypes.length === 1) {
270286
return this.prevMessageTypes[0] === MessageTypes.noTests;

src/Snapshot.ts

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
/* eslint-disable @typescript-eslint/no-unsafe-argument */
2-
/* eslint-disable @typescript-eslint/no-unsafe-return */
3-
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
4-
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
51
/**
62
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
73
*
@@ -13,17 +9,15 @@
139

1410
import traverse, {NodePath} from '@babel/traverse';
1511
import * as t from '@babel/types';
16-
import type {SnapshotResolver} from 'jest-snapshot';
17-
import {buildSnapshotResolver, utils} from 'jest-snapshot';
12+
import {SnapshotResolver, buildSnapshotResolver} from 'jest-snapshot';
13+
import * as utils from '@jest/snapshot-utils';
1814
import type {Config} from '@jest/types';
1915

2016
import {getASTfor} from './parsers/babel_parser';
2117
import type {JESParserOptions} from './parsers';
2218
import {shallowAttr} from './parsers/helper';
23-
import {SnapshotData} from 'jest-snapshot/build/types';
2419

2520
type ParserFunc = typeof getASTfor;
26-
2721
export type SnapshotNode = t.Identifier;
2822
export interface SnapshotBlock {
2923
node: SnapshotNode;
@@ -106,15 +100,20 @@ export interface SnapshotParserOptions {
106100
parserOptions?: JESParserOptions;
107101
}
108102
export default class Snapshot {
109-
_parser: ParserFunc;
103+
/** @internal */
104+
private _parser: ParserFunc;
110105

111-
_matchers: string[];
106+
/** @internal */
107+
private _matchers: string[];
112108

113-
_projectConfig?: Config.ProjectConfig;
109+
/** @internal */
110+
private _projectConfig?: Config.ProjectConfig;
114111

115-
snapshotResolver?: SnapshotResolver;
112+
/** @internal */
113+
private snapshotResolver?: SnapshotResolver;
116114

117-
_resolverPromise: Promise<SnapshotResolver>;
115+
/** @internal */
116+
private _resolverPromise: Promise<SnapshotResolver>;
118117

119118
constructor(parser?: ParserFunc, customMatchers?: string[], projectConfig?: Config.ProjectConfig) {
120119
this._parser = parser || getASTfor;
@@ -160,7 +159,8 @@ export default class Snapshot {
160159
}));
161160
}
162161

163-
async _getSnapshotResolver(): Promise<SnapshotResolver> {
162+
/** @internal */
163+
private async _getSnapshotResolver(): Promise<SnapshotResolver> {
164164
if (!this.snapshotResolver) {
165165
this.snapshotResolver = await this._resolverPromise;
166166
}
@@ -175,7 +175,7 @@ export default class Snapshot {
175175
* a SnapshotData object will be returned with all matched snapshots. If nothing matched, null will be returned.
176176
* @throws throws exception if the snapshot version mismatched or any other unexpected error.
177177
*/
178-
async getSnapshotContent(filePath: string, name: string | RegExp): Promise<string | SnapshotData | null> {
178+
async getSnapshotContent(filePath: string, name: string | RegExp): Promise<string | utils.SnapshotData | null> {
179179
const snapshotResolver = await this._getSnapshotResolver();
180180

181181
const snapshotPath = snapshotResolver.resolveSnapshotPath(filePath);
@@ -184,7 +184,7 @@ export default class Snapshot {
184184
return snapshots[name];
185185
}
186186
const regex = name;
187-
const data: SnapshotData = {};
187+
const data: utils.SnapshotData = {};
188188
Object.entries(snapshots).forEach(([key, value]) => {
189189
if (regex.test(key)) {
190190
data[key] = value;

src/__tests__/snapshot.test.ts

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,26 @@
1212

1313
import path from 'path';
1414
import Snapshot from '../Snapshot';
15-
import jestSnapshot from 'jest-snapshot';
15+
import * as jestSnapshot from 'jest-snapshot';
16+
17+
jest.mock('jest-snapshot', () => {
18+
const original = jest.requireActual('jest-snapshot');
19+
return {
20+
...original,
21+
buildSnapshotResolver: jest.fn(),
22+
};
23+
});
1624

1725
const snapshotFixturePath = path.resolve(__dirname, 'fixtures/snapshots');
1826

1927
describe('Snapshot', () => {
20-
let buildSnapshotResolverSpy: jest.SpyInstance;
2128
let snapshotHelper: Snapshot;
2229
beforeEach(() => {
23-
jest.resetAllMocks();
30+
jest.clearAllMocks();
31+
(jestSnapshot.buildSnapshotResolver as jest.Mocked<any>).mockImplementation(
32+
jest.requireActual('jest-snapshot').buildSnapshotResolver
33+
);
2434
snapshotHelper = new Snapshot();
25-
buildSnapshotResolverSpy = jest.spyOn(jestSnapshot, 'buildSnapshotResolver');
26-
});
27-
afterEach(() => {
28-
jest.restoreAllMocks();
2935
});
3036

3137
describe('getMetadata', () => {
@@ -134,7 +140,7 @@ describe('Snapshot', () => {
134140
});
135141
it('when the resolver is not yet ready', () => {
136142
// simulate when buildSnapshotResolver did not resolve yet
137-
buildSnapshotResolverSpy.mockImplementation((() => {
143+
(jestSnapshot.buildSnapshotResolver as jest.Mocked<any>).mockImplementation((() => {
138144
// eslint-disable-next-line @typescript-eslint/no-empty-function
139145
return new Promise(() => {});
140146
}) as any);
@@ -239,7 +245,7 @@ describe('Snapshot', () => {
239245
const snapshot = new Snapshot(undefined, undefined, customConfig);
240246
const filePath = path.join(snapshotFixturePath, 'inline-and-each.example');
241247
await snapshot.getSnapshotContent(filePath, /not existing test/);
242-
expect(buildSnapshotResolverSpy).toHaveBeenCalledWith(customConfig, expect.any(Function));
248+
expect(jestSnapshot.buildSnapshotResolver).toHaveBeenCalledWith(customConfig, expect.any(Function));
243249
});
244250
});
245251
});

src/test_reconciler.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ export type TestFileAssertionStatus = Omit<JestFileResults, 'status' | 'assertio
5252
* at a file level, generating useful error messages and providing a nice API.
5353
*/
5454
export default class TestReconciler {
55-
fileStatuses: {[key: string]: TestFileAssertionStatus};
55+
/** @internal */
56+
private fileStatuses: {[key: string]: TestFileAssertionStatus};
5657

5758
constructor() {
5859
this.fileStatuses = {};
@@ -93,7 +94,8 @@ export default class TestReconciler {
9394
// we don't get this as structured data, but what we get
9495
// is useful enough to make it for ourselves
9596

96-
mapAssertions(filename: string, assertions: JestAssertionResults[]): TestAssertionStatus[] {
97+
/** @internal */
98+
private mapAssertions(filename: string, assertions: JestAssertionResults[]): TestAssertionStatus[] {
9799
// convert jest location (column is 0-based and line is 1-based) to all 0-based location used internally in this package
98100
/* eslint-disable no-param-reassign */
99101
const convertJestLocation = (jestLocation?: CodeLocation) => {
@@ -135,7 +137,8 @@ export default class TestReconciler {
135137
}
136138

137139
// Do everything we can to try make a one-liner from the error report
138-
sanitizeShortErrorMessage(string: string): string {
140+
/** @internal */
141+
private sanitizeShortErrorMessage(string: string): string {
139142
if (string.includes('does not match stored snapshot')) {
140143
return 'Snapshot has changed';
141144
}
@@ -154,13 +157,15 @@ export default class TestReconciler {
154157
}
155158

156159
// Pull the line out from the stack trace
157-
lineOfError(message: string, filePath: string): number | undefined {
160+
/** @internal */
161+
private lineOfError(message: string, filePath: string): number | undefined {
158162
const filename = path.basename(filePath);
159163
const restOfTrace = message.split(filename, 2)[1];
160164
return restOfTrace ? parseInt(restOfTrace.split(':')[1], 10) : undefined;
161165
}
162166

163-
statusToReconciliationState(status: string): TestReconciliationState {
167+
/** @internal */
168+
private statusToReconciliationState(status: string): TestReconciliationState {
164169
switch (status) {
165170
case 'passed':
166171
return 'KnownSuccess';

tsconfig.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@
99
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
1010
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
1111
},
12-
"include": ["./src/**/*.ts", "src/__tests__/parsers/helper.test.ts"]
12+
"include": ["./src/**/*.ts"],
1313
}

tsconfig.prod.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
"sourceMap": false, // Disable source maps for production
55
"declaration": false, // Disable declaration files generation
66
"outDir": "./build", // Output directory for compiled JS files
7-
"removeComments": true // Optional: Remove comments in the production build
7+
"removeComments": true, // Optional: Remove comments in the production build
8+
"stripInternal": true,
89
},
910
"exclude": [
1011
"**/__tests__/**", // Exclude all test files

tsconfig.types.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"extends": "./tsconfig.prod.json",
3+
"compilerOptions": {
4+
"removeComments": false, // Optional: Remove comments in the production build
5+
},
6+
}

0 commit comments

Comments
 (0)