oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
71.09k stars 2.47k forks source link

\x in the snapshot data creates a corrupted snapshot #10868

Open pragmatta opened 1 week ago

pragmatta commented 1 week ago

Discussed in https://github.com/oven-sh/bun/discussions/10402

Having \x in the snapshot data creates a corrupted snapshot that can't be read. For example this test

test("dummy", () => {
        expect("\"x\\x\"").toMatchSnapshot()
})

generates snapshot

exports[`dummy 1`] = `""x\x""`;

Which is invalid Javascript (I assume the file gets evaluated) as the \x is treated as a hex string and parsing the snapshot fails. Instead running the test will write it in the snapshot over and over again (and creates a problem that is hard to diagnose).

pragmatta commented 1 week ago

Also when the data does not result in an invalide escapepe sequence, it fails to properly parse out snapshots, resulting in test fails.

For example test:

    test("dummy", () => {
        expect({foo:"h\\i"}).toMatchSnapshot()
    })

results in snapshot:

exports[`dummy 1`] = `
{
  "foo": "h\i",
}
`;

that fails the test because of parsing mismatch:

37 |     test("dummy", () => {
38 |         expect({foo:"h\\i"}).toMatchSnapshot()
             ^
error: expect(received).toMatchSnapshot(expected)

Expected:
{
  "foo": "hi",
}

Received:
{
  "foo": "h\i",
}
Jarred-Sumner commented 1 week ago

The state of our snapshots implementation isn't great.

pragmatta commented 1 week ago

The state of our snapshots implementation isn't great.

Is there a way to read/parse the snapshots (easily), how does Bun do it? I want to cross-reference outputs of different implementations of same abstraction. I tried requiring the snapshot-file and reads an [object Module] but has no properties..

const snapshots = require("./__snapshots__/OINOApi.test.ts.snap")
const keys = Object.keys(snapshots)
for (const key of keys) {
  console.log(key, snapshots[key])
}
pragmatta commented 1 week ago

I tried requiring the snapshot-file and reads an [object Module] but has no properties..

Figured this one out, the extension of the file needs to be .js for it to work. Node seems to not care about this.