|
| 1 | +import { ng } from '../../utils/process'; |
| 2 | +import { appendToFile, replaceInFile, readFile } from '../../utils/fs'; |
| 3 | +import { applyVitestBuilder } from '../../utils/vitest'; |
| 4 | +import assert from 'node:assert/strict'; |
| 5 | + |
| 6 | +export default async function () { |
| 7 | + // Set up the test project to use the vitest runner |
| 8 | + await applyVitestBuilder(); |
| 9 | + |
| 10 | + // Add snapshot assertions to the test file |
| 11 | + await appendToFile( |
| 12 | + 'src/app/app.spec.ts', |
| 13 | + ` |
| 14 | + it('should match file snapshot', () => { |
| 15 | + const fixture = TestBed.createComponent(App); |
| 16 | + const app = fixture.componentInstance; |
| 17 | + expect((app as any).title()).toMatchSnapshot(); |
| 18 | + }); |
| 19 | +
|
| 20 | + it('should match inline snapshot', () => { |
| 21 | + const fixture = TestBed.createComponent(App); |
| 22 | + const app = fixture.componentInstance; |
| 23 | + expect((app as any).title()).toMatchInlineSnapshot(); |
| 24 | + }); |
| 25 | + `, |
| 26 | + ); |
| 27 | + |
| 28 | + // First run: create snapshots |
| 29 | + const { stdout: firstRunStdout } = await ng('test'); |
| 30 | + assert.match( |
| 31 | + firstRunStdout, |
| 32 | + /Snapshots\s+2 written/, |
| 33 | + 'Snapshots were not written on the first run.', |
| 34 | + ); |
| 35 | + |
| 36 | + const specContent = await readFile('src/app/app.spec.ts'); |
| 37 | + assert.match( |
| 38 | + specContent, |
| 39 | + /toMatchInlineSnapshot\(`"test-project"`\)/, |
| 40 | + 'Inline snapshot was not written to the spec file.', |
| 41 | + ); |
| 42 | + |
| 43 | + const snapshotContent = await readFile('src/app/__snapshots__/app.spec.ts.snap'); |
| 44 | + assert.match( |
| 45 | + snapshotContent, |
| 46 | + /exports\[`should match file snapshot 1`\] = `"test-project"`;/, |
| 47 | + 'File snapshot was not written to disk.', |
| 48 | + ); |
| 49 | + |
| 50 | + // Second run: tests should pass with existing snapshots |
| 51 | + await ng('test'); |
| 52 | + |
| 53 | + // Modify component to break snapshots |
| 54 | + await replaceInFile('src/app/app.ts', 'test-project', 'Snapshot is broken!'); |
| 55 | + |
| 56 | + // Third run: tests should fail with snapshot mismatch |
| 57 | + await assert.rejects( |
| 58 | + () => ng('test'), |
| 59 | + (err: any) => { |
| 60 | + assert.match( |
| 61 | + err.toString(), |
| 62 | + /Snapshots\s+2 failed/, |
| 63 | + 'Expected snapshot mismatch error, but a different error occurred.', |
| 64 | + ); |
| 65 | + return true; |
| 66 | + }, |
| 67 | + 'Snapshot mismatch did not cause the test to fail.', |
| 68 | + ); |
| 69 | +} |
0 commit comments