Skip to content

Commit

Permalink
feat: async toThrowErrorMatchingSnapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
ChALkeR committed Jul 12, 2024
1 parent dfbf0a4 commit a3bbfdc
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 2 additions & 0 deletions __test__/jest/__snapshots__/snapshot.test.js.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`async errors 1`] = `"slow but nah"`;

exports[`complex 1`] = `
[
10,
Expand Down
5 changes: 5 additions & 0 deletions __test__/jest/snapshot.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,8 @@ it('errors', () => {
throw new RangeError('Out of something')
}).toThrowErrorMatchingInlineSnapshot('"Out of something"')
})

it('async errors', async () => {
await expect(Promise.reject(new TypeError('slow but nah'))).rejects.toThrowErrorMatchingSnapshot()
await expect(Promise.resolve(new Error('ok'))).resolves.toThrowErrorMatchingInlineSnapshot('"ok"')
})
14 changes: 11 additions & 3 deletions src/jest.snapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,19 @@ function wrapContextName(fn) {
}
}

const throws = (fn, check) =>
const throws = ([fn, , wrapped], check) => {
if (wrapped) {
// Seems that we got unwrapped promise result
// We need to be careful to not consume 2 assertion counters, so wrap with an if
if (!(fn && fn instanceof Error)) getAssert().fail('Received function did not throw')
return check(fn.message)
}

getAssert().throws(fn, (e) => {
check(e.message) // jest stores only messages for errors
return true
})
}

const snapInline = (obj, inline) => {
assert(inline !== undefined, 'Inline Snapshots generation is not supported')
Expand Down Expand Up @@ -103,8 +111,8 @@ const snapOnDisk = (obj) =>
expect.extend({
toMatchInlineSnapshot: (obj, i) => wrap(() => snapInline(obj, i)),
toMatchSnapshot: (obj) => wrap(() => snapOnDisk(obj)),
toThrowErrorMatchingInlineSnapshot: (f, i) => wrap(() => throws(f, (msg) => snapInline(msg, i))),
toThrowErrorMatchingSnapshot: (f) => wrap(() => throws(f, (msg) => snapOnDisk(msg))),
toThrowErrorMatchingInlineSnapshot: (...a) => wrap(() => throws(a, (m) => snapInline(m, a[1]))),
toThrowErrorMatchingSnapshot: (...a) => wrap(() => throws(a, (m) => snapOnDisk(m))),
})

expect.addSnapshotSerializer = (plugin) => plugins.push(plugin)

0 comments on commit a3bbfdc

Please sign in to comment.