|
| 1 | +import { expect, test } from 'vitest' |
| 2 | + |
| 3 | +test('basic', () => { |
| 4 | + // example from docs/guide/snapshot.md |
| 5 | + |
| 6 | + const bar = { |
| 7 | + foo: { |
| 8 | + x: 1, |
| 9 | + y: 2, |
| 10 | + }, |
| 11 | + } |
| 12 | + |
| 13 | + // without custom serializer |
| 14 | + expect(bar).toMatchInlineSnapshot(` |
| 15 | + { |
| 16 | + "foo": { |
| 17 | + "x": 1, |
| 18 | + "y": 2, |
| 19 | + }, |
| 20 | + } |
| 21 | + `) |
| 22 | + |
| 23 | + // with custom serializer |
| 24 | + expect.addSnapshotSerializer({ |
| 25 | + serialize(val, config, indentation, depth, refs, printer) { |
| 26 | + return `Pretty foo: ${printer( |
| 27 | + val.foo, |
| 28 | + config, |
| 29 | + indentation, |
| 30 | + depth, |
| 31 | + refs, |
| 32 | + )}` |
| 33 | + }, |
| 34 | + test(val) { |
| 35 | + return val && Object.prototype.hasOwnProperty.call(val, 'foo') |
| 36 | + }, |
| 37 | + }) |
| 38 | + |
| 39 | + expect(bar).toMatchInlineSnapshot(` |
| 40 | + Pretty foo: { |
| 41 | + "x": 1, |
| 42 | + "y": 2, |
| 43 | + } |
| 44 | + `) |
| 45 | +}) |
| 46 | + |
| 47 | +test('throwning snapshot', () => { |
| 48 | + // example from https://github.com/vitest-dev/vitest/issues/3655 |
| 49 | + |
| 50 | + class ErrorWithDetails extends Error { |
| 51 | + readonly details: unknown |
| 52 | + |
| 53 | + constructor(message: string, options: ErrorOptions & { details: unknown }) { |
| 54 | + super(message, options) |
| 55 | + this.details = options.details |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // without custom serializer |
| 60 | + const error = new ErrorWithDetails('some-error', { |
| 61 | + details: 'some-detail', |
| 62 | + }) |
| 63 | + expect(error).toMatchInlineSnapshot(`[Error: some-error]`) |
| 64 | + expect(() => { |
| 65 | + throw error |
| 66 | + }).toThrowErrorMatchingInlineSnapshot(`[Error: some-error]`) |
| 67 | + |
| 68 | + // with custom serializer |
| 69 | + expect.addSnapshotSerializer({ |
| 70 | + serialize(val, config, indentation, depth, refs, printer) { |
| 71 | + const error = val as ErrorWithDetails |
| 72 | + return `Pretty ${error.message}: ${printer( |
| 73 | + error.details, |
| 74 | + config, |
| 75 | + indentation, |
| 76 | + depth, |
| 77 | + refs, |
| 78 | + )}` |
| 79 | + }, |
| 80 | + test(val) { |
| 81 | + return val && val instanceof ErrorWithDetails |
| 82 | + }, |
| 83 | + }) |
| 84 | + expect(error).toMatchInlineSnapshot(`Pretty some-error: "some-detail"`) |
| 85 | + expect(() => { |
| 86 | + throw error |
| 87 | + }).toThrowErrorMatchingInlineSnapshot(`Pretty some-error: "some-detail"`) |
| 88 | +}) |
0 commit comments