|
| 1 | +import assert from 'node:assert' |
| 2 | +import fs from 'node:fs' |
| 3 | +import test from 'node:test' |
| 4 | +import { startVitest } from 'vitest/node' |
| 5 | + |
| 6 | +let vitest |
| 7 | + |
| 8 | +test.after(async () => { |
| 9 | + await vitest?.close() |
| 10 | +}) |
| 11 | + |
| 12 | +test('update snapshot', async () => { |
| 13 | + // setup wrong snapshot value |
| 14 | + const snapshotPath = './fixtures/update-snapshot/__snapshots__/basic.test.ts.snap' |
| 15 | + await editFile(snapshotPath, data => data.replace('`1`', '`2`')) |
| 16 | + |
| 17 | + // run vitest watch mode |
| 18 | + const result = await wrapExit(() => startVitest('test', [], { |
| 19 | + watch: true, |
| 20 | + root: './fixtures/update-snapshot', |
| 21 | + reporters: ['tap-flat'], // use simple reporter to not pollute stdout |
| 22 | + browser: { headless: true }, |
| 23 | + })) |
| 24 | + vitest = result.value |
| 25 | + assert.ok(vitest) |
| 26 | + |
| 27 | + // test fails |
| 28 | + assert.equal(result.exitCode, 1) |
| 29 | + assert.equal(vitest.state.getFiles()[0].result.state, 'fail') |
| 30 | + |
| 31 | + // updateSnapshot API to simulate "u" commmand |
| 32 | + await vitest.updateSnapshot() |
| 33 | + |
| 34 | + // verify snapshot value is updated |
| 35 | + const snapshotData = await fs.promises.readFile(snapshotPath, 'utf-8') |
| 36 | + assert.match(snapshotData, /`1`/) |
| 37 | + |
| 38 | + // test passes |
| 39 | + assert.equal(vitest.state.getFiles()[0].result.state, 'pass') |
| 40 | +}) |
| 41 | + |
| 42 | +/** |
| 43 | + * @param {string} filepath |
| 44 | + * @param {(data: string) => string} edit |
| 45 | + */ |
| 46 | +async function editFile(filepath, edit) { |
| 47 | + const data = await fs.promises.readFile(filepath, 'utf-8') |
| 48 | + await fs.promises.writeFile(filepath, edit(data)) |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * run function and return mutated exitCode while preserving current exitCode |
| 53 | + * @param {() => any} f |
| 54 | + */ |
| 55 | +async function wrapExit(f) { |
| 56 | + const prevExitCode = process.exitCode |
| 57 | + const prevExit = process.exit |
| 58 | + process.exit = () => {} |
| 59 | + /** @type {{ value?: any, exitCode?: number }} */ |
| 60 | + const result = {} |
| 61 | + try { |
| 62 | + result.value = await f() |
| 63 | + } |
| 64 | + finally { |
| 65 | + result.exitCode = process.exitCode |
| 66 | + process.exitCode = prevExitCode |
| 67 | + process.exit = prevExit |
| 68 | + } |
| 69 | + return result |
| 70 | +} |
0 commit comments