Skip to content

Commit

Permalink
feat: matchers support in toMatchSnapshot()
Browse files Browse the repository at this point in the history
  • Loading branch information
ChALkeR committed Jul 16, 2024
1 parent 7d406e9 commit 8948e7b
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 2 deletions.
15 changes: 15 additions & 0 deletions __test__/jest/__snapshots__/snapshot.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,21 @@ exports[`nested test test A 2`] = `
]
`;
exports[`property matchers will check the matchers and pass 1`] = `
{
"createdAt": Any<Date>,
"id": Any<Number>,
"name": "LeBron James",
}
`;
exports[`property matchers will check the values and pass 1`] = `
{
"createdAt": Any<Date>,
"name": "Bond... James Bond",
}
`;
exports[`simple 1`] = `10`;
exports[`simple 2`] = `null`;
Expand Down
33 changes: 33 additions & 0 deletions __test__/jest/snapshot.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,36 @@ describe('weird names', () => {
expect(42).toMatchSnapshot()
})
})

// https://jestjs.io/docs/snapshot-testing#property-matchers

describe('property matchers', () => {
it('will check the matchers and pass', () => {
expect.assertions(1) // ensure we don't over-consume

const user = {
createdAt: new Date(),
id: Math.floor(Math.random() * 20),
name: 'LeBron James',
}

expect(user).toMatchSnapshot({
createdAt: expect.any(Date),
id: expect.any(Number),
})
})

it('will check the values and pass', () => {
expect.assertions(1) // ensure we don't over-consume

const user = {
createdAt: new Date(),
name: 'Bond... James Bond',
}

expect(user).toMatchSnapshot({
createdAt: expect.any(Date),
name: 'Bond... James Bond',
})
})
})
13 changes: 11 additions & 2 deletions src/jest.snapshot.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,16 @@ const snapInline = (obj, inline) => {
getAssert().strictEqual(serialize(obj).trim(), inline.trim())
}

const snapOnDisk = (obj) => {
const snapOnDisk = (orig, matcher) => {
if (matcher) {
expect(orig).toMatchObject(matcher)
// If we passed, make appear that the above call never happened
const state = expect.getState()
state.assertionCalls--
state.numPassingAsserts--
}

const obj = matcher ? { ...orig, ...matcher } : orig
const escape = (str) => str.replaceAll(/([\\`])/gu, '\\$1')

if (!maybeSetupJestSnapshots()) {
Expand Down Expand Up @@ -154,7 +163,7 @@ const snapOnDisk = (obj) => {

expect.extend({
toMatchInlineSnapshot: (obj, i) => wrap(() => snapInline(obj, i)),
toMatchSnapshot: (obj) => wrap(() => snapOnDisk(obj)),
toMatchSnapshot: (obj, matcher) => wrap(() => snapOnDisk(obj, matcher)),
toThrowErrorMatchingInlineSnapshot: (...a) => wrap(() => throws(a, (m) => snapInline(m, a[1]))),
toThrowErrorMatchingSnapshot: (...a) => wrap(() => throws(a, (m) => snapOnDisk(m))),
})
Expand Down

0 comments on commit 8948e7b

Please sign in to comment.