-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Expand file tree
/
Copy pathsnapshot.ts
More file actions
79 lines (69 loc) · 2.5 KB
/
snapshot.ts
File metadata and controls
79 lines (69 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { ng } from '../../utils/process';
import { replaceInFile, readFile, writeFile } from '../../utils/fs';
import { applyVitestBuilder } from '../../utils/vitest';
import assert from 'node:assert/strict';
import { stripVTControlCharacters } from 'node:util';
export default async function () {
// Set up the test project to use the vitest runner
await applyVitestBuilder();
// Add snapshot assertions to the test file
await replaceInFile(
'src/app/app.spec.ts',
`describe('App', () => {`,
`
describe('App', () => {
it('should match file snapshot', () => {
const fixture = TestBed.createComponent(App);
const app = fixture.componentInstance;
expect((app as any).title()).toMatchSnapshot();
});
it('should match inline snapshot', () => {
const fixture = TestBed.createComponent(App);
const app = fixture.componentInstance;
expect((app as any).title()).toMatchInlineSnapshot();
});
`,
);
// Synchronize line endings for Vitest which currently may miscalculate line counts
// with mixed file line endings.
let content = await readFile('src/app/app.spec.ts');
content = content.replace(/\r\n/g, '\n');
content = content.replace(/\r/g, '\n');
await writeFile('src/app/app.spec.ts', content);
// First run: create snapshots
const { stdout: firstRunStdout } = await ng('test');
assert.match(
stripVTControlCharacters(firstRunStdout),
/Snapshots\s+2 written/,
'Snapshots were not written on the first run.',
);
const specContent = await readFile('src/app/app.spec.ts');
assert.match(
specContent,
/toMatchInlineSnapshot\(`"test-project"`\)/,
'Inline snapshot was not written to the spec file.',
);
const snapshotContent = await readFile('src/app/__snapshots__/app.spec.ts.snap');
assert.match(
snapshotContent,
/exports\[`App > should match file snapshot 1`\] = `"test-project"`;/,
'File snapshot was not written to disk.',
);
// Second run: tests should pass with existing snapshots
await ng('test');
// Modify component to break snapshots
await replaceInFile('src/app/app.ts', 'test-project', 'Snapshot is broken!');
// Third run: tests should fail with snapshot mismatch
await assert.rejects(
() => ng('test'),
(err: any) => {
assert.match(
stripVTControlCharacters(err.toString()),
/Snapshots\s+2 failed/,
'Expected snapshot mismatch error, but a different error occurred.',
);
return true;
},
'Snapshot mismatch did not cause the test to fail.',
);
}