@vitest/snapshot 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-Present Anthony Fu <https://github.com/antfu>
4
+ Copyright (c) 2021-Present Matias Capeletto <https://github.com/patak-dev>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # @vitest/snapshot
2
+
3
+ Lightweight implementation of Jest's snapshots.
4
+
5
+ ## Usage
6
+
7
+ ```js
8
+ import { SnapshotClient } from '@vitest/snapshot'
9
+ import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment'
10
+ import { SnapshotManager } from '@vitest/snapshot/manager'
11
+
12
+ export class CustomSnapshotClient extends SnapshotClient {
13
+ // by default, @vitest/snapshot checks equality with `!==`
14
+ // you need to provide your own equality check implementation
15
+ // this function is called when `.toMatchSnapshot({ property: 1 })` is called
16
+ equalityCheck(received, expected) {
17
+ return equals(received, expected, [iterableEquality, subsetEquality])
18
+ }
19
+ }
20
+
21
+ const client = new CustomSnapshotClient()
22
+ // class that implements snapshot saving and reading
23
+ // by default uses fs module, but you can provide your own implementation depending on the environment
24
+ const environment = new NodeSnapshotEnvironment()
25
+
26
+ function getCurrentFilepath() {
27
+ return '/file.spec.ts'
28
+ }
29
+ function getCurrentTestName() {
30
+ return 'test1'
31
+ }
32
+
33
+ function wrapper(received) {
34
+ function __INLINE_SNAPSHOT__(inlineSnapshot, message) {
35
+ client.assert({
36
+ received,
37
+ message,
38
+ isInline: true,
39
+ inlineSnapshot,
40
+ // you need to implement this yourselves,
41
+ // this depends on your runner
42
+ filepath: getCurrentFilepath(),
43
+ name: getCurrentTestName(),
44
+ })
45
+ }
46
+ return {
47
+ // the name is hard-coded, it should be inside another function, so Vitest can find the actual test file where it was called (parses call stack trace + 2)
48
+ // you can override this behaviour in SnapshotState's `_inferInlineSnapshotStack` method by providing your own SnapshotState to SnapshotClient constructor
49
+ toMatchInlineSnapshot: (...args) => __INLINE_SNAPSHOT__(...args),
50
+ }
51
+ }
52
+
53
+ const options = {
54
+ updateSnapshot: 'new',
55
+ snapshotEnvironment: environment,
56
+ }
57
+
58
+ await client.setTest(getCurrentFilepath(), getCurrentTestName(), options)
59
+
60
+ // uses "pretty-format", so it requires quotes
61
+ // also naming is hard-coded when parsing test files
62
+ wrapper('text 1').toMatchInlineSnapshot()
63
+ wrapper('text 2').toMatchInlineSnapshot('"text 2"')
64
+
65
+ const result = await client.resetCurrent() // this saves files and returns SnapshotResult
66
+
67
+ // you can use manager to manage several clients
68
+ const manager = new SnapshotManager(options)
69
+ manager.add(result)
70
+
71
+ // do something
72
+ // and then read the summary
73
+
74
+ console.log(manager.summary)
75
+ ```
@@ -0,0 +1,12 @@
1
+ interface SnapshotEnvironment {
2
+ getVersion(): string;
3
+ getHeader(): string;
4
+ resolvePath(filepath: string): Promise<string>;
5
+ resolveRawPath(testPath: string, rawPath: string): Promise<string>;
6
+ prepareDirectory(filepath: string): Promise<void>;
7
+ saveSnapshotFile(filepath: string, snapshot: string): Promise<void>;
8
+ readSnapshotFile(filepath: string): Promise<string | null>;
9
+ removeSnapshotFile(filepath: string): Promise<void>;
10
+ }
11
+
12
+ export { SnapshotEnvironment as S };
@@ -0,0 +1,14 @@
1
+ import { S as SnapshotEnvironment } from './environment-8fbbf71b.js';
2
+
3
+ declare class NodeSnapshotEnvironment implements SnapshotEnvironment {
4
+ getVersion(): string;
5
+ getHeader(): string;
6
+ resolveRawPath(testPath: string, rawPath: string): Promise<string>;
7
+ resolvePath(filepath: string): Promise<string>;
8
+ prepareDirectory(filepath: string): Promise<void>;
9
+ saveSnapshotFile(filepath: string, snapshot: string): Promise<void>;
10
+ readSnapshotFile(filepath: string): Promise<string | null>;
11
+ removeSnapshotFile(filepath: string): Promise<void>;
12
+ }
13
+
14
+ export { NodeSnapshotEnvironment, SnapshotEnvironment };
@@ -0,0 +1,40 @@
1
+ import { promises, existsSync } from 'node:fs';
2
+ import { isAbsolute, resolve, dirname, join, basename } from 'pathe';
3
+
4
+ class NodeSnapshotEnvironment {
5
+ getVersion() {
6
+ return "1";
7
+ }
8
+ getHeader() {
9
+ return `// Snapshot v${this.getVersion()}`;
10
+ }
11
+ async resolveRawPath(testPath, rawPath) {
12
+ return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath);
13
+ }
14
+ async resolvePath(filepath) {
15
+ return join(
16
+ join(
17
+ dirname(filepath),
18
+ "__snapshots__"
19
+ ),
20
+ `${basename(filepath)}.snap`
21
+ );
22
+ }
23
+ async prepareDirectory(filepath) {
24
+ await promises.mkdir(filepath, { recursive: true });
25
+ }
26
+ async saveSnapshotFile(filepath, snapshot) {
27
+ await promises.writeFile(filepath, snapshot, "utf-8");
28
+ }
29
+ async readSnapshotFile(filepath) {
30
+ if (!existsSync(filepath))
31
+ return null;
32
+ return promises.readFile(filepath, "utf-8");
33
+ }
34
+ async removeSnapshotFile(filepath) {
35
+ if (existsSync(filepath))
36
+ await promises.unlink(filepath);
37
+ }
38
+ }
39
+
40
+ export { NodeSnapshotEnvironment };
@@ -0,0 +1,59 @@
1
+ import { OptionsReceived } from 'pretty-format';
2
+ import { S as SnapshotEnvironment } from './environment-8fbbf71b.js';
3
+
4
+ interface RawSnapshotInfo {
5
+ file: string;
6
+ readonly?: boolean;
7
+ content?: string;
8
+ }
9
+
10
+ type SnapshotData = Record<string, string>;
11
+ type SnapshotUpdateState = 'all' | 'new' | 'none';
12
+ interface SnapshotStateOptions {
13
+ updateSnapshot: SnapshotUpdateState;
14
+ snapshotEnvironment: SnapshotEnvironment;
15
+ expand?: boolean;
16
+ snapshotFormat?: OptionsReceived;
17
+ resolveSnapshotPath?: (path: string, extension: string) => string;
18
+ }
19
+ interface SnapshotMatchOptions {
20
+ testName: string;
21
+ received: unknown;
22
+ key?: string;
23
+ inlineSnapshot?: string;
24
+ isInline: boolean;
25
+ error?: Error;
26
+ rawSnapshot?: RawSnapshotInfo;
27
+ }
28
+ interface SnapshotResult {
29
+ filepath: string;
30
+ added: number;
31
+ fileDeleted: boolean;
32
+ matched: number;
33
+ unchecked: number;
34
+ uncheckedKeys: Array<string>;
35
+ unmatched: number;
36
+ updated: number;
37
+ }
38
+ interface UncheckedSnapshot {
39
+ filePath: string;
40
+ keys: Array<string>;
41
+ }
42
+ interface SnapshotSummary {
43
+ added: number;
44
+ didUpdate: boolean;
45
+ failure: boolean;
46
+ filesAdded: number;
47
+ filesRemoved: number;
48
+ filesRemovedList: Array<string>;
49
+ filesUnmatched: number;
50
+ filesUpdated: number;
51
+ matched: number;
52
+ total: number;
53
+ unchecked: number;
54
+ uncheckedKeysByFile: Array<UncheckedSnapshot>;
55
+ unmatched: number;
56
+ updated: number;
57
+ }
58
+
59
+ export { RawSnapshotInfo as R, SnapshotStateOptions as S, UncheckedSnapshot as U, SnapshotMatchOptions as a, SnapshotResult as b, SnapshotData as c, SnapshotUpdateState as d, SnapshotSummary as e };
@@ -0,0 +1,112 @@
1
+ import { S as SnapshotStateOptions, a as SnapshotMatchOptions, b as SnapshotResult, R as RawSnapshotInfo } from './index-2c775746.js';
2
+ export { c as SnapshotData, e as SnapshotSummary, d as SnapshotUpdateState, U as UncheckedSnapshot } from './index-2c775746.js';
3
+ import { S as SnapshotEnvironment } from './environment-8fbbf71b.js';
4
+ import { Plugin, Plugins } from 'pretty-format';
5
+
6
+ interface ParsedStack {
7
+ method: string;
8
+ file: string;
9
+ line: number;
10
+ column: number;
11
+ }
12
+
13
+ /**
14
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
15
+ *
16
+ * This source code is licensed under the MIT license found in the
17
+ * LICENSE file in the root directory of this source tree.
18
+ */
19
+
20
+ interface SnapshotReturnOptions {
21
+ actual: string;
22
+ count: number;
23
+ expected?: string;
24
+ key: string;
25
+ pass: boolean;
26
+ }
27
+ interface SaveStatus {
28
+ deleted: boolean;
29
+ saved: boolean;
30
+ }
31
+ declare class SnapshotState {
32
+ testFilePath: string;
33
+ snapshotPath: string;
34
+ private _counters;
35
+ private _dirty;
36
+ private _updateSnapshot;
37
+ private _snapshotData;
38
+ private _initialData;
39
+ private _inlineSnapshots;
40
+ private _rawSnapshots;
41
+ private _uncheckedKeys;
42
+ private _snapshotFormat;
43
+ private _environment;
44
+ private _fileExists;
45
+ added: number;
46
+ expand: boolean;
47
+ matched: number;
48
+ unmatched: number;
49
+ updated: number;
50
+ private constructor();
51
+ static create(testFilePath: string, options: SnapshotStateOptions): Promise<SnapshotState>;
52
+ get environment(): SnapshotEnvironment;
53
+ markSnapshotsAsCheckedForTest(testName: string): void;
54
+ protected _inferInlineSnapshotStack(stacks: ParsedStack[]): ParsedStack | null;
55
+ private _addSnapshot;
56
+ clear(): void;
57
+ save(): Promise<SaveStatus>;
58
+ getUncheckedCount(): number;
59
+ getUncheckedKeys(): Array<string>;
60
+ removeUncheckedKeys(): void;
61
+ match({ testName, received, key, inlineSnapshot, isInline, error, rawSnapshot, }: SnapshotMatchOptions): SnapshotReturnOptions;
62
+ pack(): Promise<SnapshotResult>;
63
+ }
64
+
65
+ interface AssertOptions {
66
+ received: unknown;
67
+ filepath?: string;
68
+ name?: string;
69
+ message?: string;
70
+ isInline?: boolean;
71
+ properties?: object;
72
+ inlineSnapshot?: string;
73
+ error?: Error;
74
+ errorMessage?: string;
75
+ rawSnapshot?: RawSnapshotInfo;
76
+ }
77
+ declare class SnapshotClient {
78
+ private Service;
79
+ filepath?: string;
80
+ name?: string;
81
+ snapshotState: SnapshotState | undefined;
82
+ snapshotStateMap: Map<string, SnapshotState>;
83
+ constructor(Service?: typeof SnapshotState);
84
+ setTest(filepath: string, name: string, options: SnapshotStateOptions): Promise<void>;
85
+ getSnapshotState(filepath: string): SnapshotState;
86
+ clearTest(): void;
87
+ skipTestSnapshots(name: string): void;
88
+ /**
89
+ * Should be overridden by the consumer.
90
+ *
91
+ * Vitest checks equality with @vitest/expect.
92
+ */
93
+ equalityCheck(received: unknown, expected: unknown): boolean;
94
+ assert(options: AssertOptions): void;
95
+ assertRaw(options: AssertOptions): Promise<void>;
96
+ resetCurrent(): Promise<SnapshotResult | null>;
97
+ clear(): void;
98
+ }
99
+
100
+ /**
101
+ * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
102
+ *
103
+ * This source code is licensed under the MIT license found in the
104
+ * LICENSE file in the root directory of this source tree.
105
+ */
106
+
107
+ declare function addSerializer(plugin: Plugin): void;
108
+ declare function getSerializers(): Plugins;
109
+
110
+ declare function stripSnapshotIndentation(inlineSnapshot: string): string;
111
+
112
+ export { SnapshotClient, SnapshotMatchOptions, SnapshotResult, SnapshotState, SnapshotStateOptions, addSerializer, getSerializers, stripSnapshotIndentation };