diff --git a/__test__/jest/__snapshots__/snapshot.test.js.snap b/__test__/jest/__snapshots__/snapshot.test.js.snap index 5e3f5e4..e033c16 100644 --- a/__test__/jest/__snapshots__/snapshot.test.js.snap +++ b/__test__/jest/__snapshots__/snapshot.test.js.snap @@ -148,6 +148,21 @@ exports[`nested test test A 2`] = ` ] `; +exports[`property matchers will check the matchers and pass 1`] = ` +{ + "createdAt": Any, + "id": Any, + "name": "LeBron James", +} +`; + +exports[`property matchers will check the values and pass 1`] = ` +{ + "createdAt": Any, + "name": "Bond... James Bond", +} +`; + exports[`simple 1`] = `10`; exports[`simple 2`] = `null`; diff --git a/__test__/jest/snapshot.test.js b/__test__/jest/snapshot.test.js index e183753..8b6b024 100644 --- a/__test__/jest/snapshot.test.js +++ b/__test__/jest/snapshot.test.js @@ -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', + }) + }) +}) diff --git a/src/jest.snapshot.js b/src/jest.snapshot.js index 4790176..80ab4f1 100644 --- a/src/jest.snapshot.js +++ b/src/jest.snapshot.js @@ -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()) { @@ -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))), })