From 53230a10b36ae8528dba9db8dcde8d8a6c52b5f7 Mon Sep 17 00:00:00 2001 From: "Jeroen Claassens (Favna)" Date: Mon, 29 Apr 2019 08:17:19 +0200 Subject: [PATCH] Jest: Added Generic for "toMatchObject" function (#35033) * Add generic to toMatchObject * Cover feedback from @wsmd --- types/jest/index.d.ts | 20 +++++++++++++++++++- types/jest/jest-tests.ts | 2 ++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 86a627c61d..61aca7b397 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -18,6 +18,7 @@ // Sebastian Sebald // Andy // Antoine Brault +// Jeroen Claassens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 @@ -757,8 +758,25 @@ declare namespace jest { toMatch(expected: string | RegExp): R; /** * Used to check that a JavaScript object matches a subset of the properties of an object + * + * Optionally, you can provide an object to use as Generic type for the expected value. + * This ensures that the matching object matches the structure of the provided object-like type. + * + * @example + * + * type House = { + * bath: boolean; + * bedrooms: number; + * kitchen: { + * amenities: string[]; + * area: number; + * wallColor: string; + * } + * }; + * + * expect(desiredHouse).toMatchObject(...standardHouse, kitchen: {area: 20}) // wherein standardHouse is some base object of type House */ - toMatchObject(expected: {} | any[]): R; + toMatchObject(expected: E): R; /** * This ensures that a value matches the most recent snapshot with property matchers. * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index b3356f044d..04d25ce5e9 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -830,6 +830,8 @@ describe("", () => { expect({ abc: "def" }).toMatchObject({ abc: "def" }); expect({}).toMatchObject([{}, {}]); expect({ abc: "def" }).toMatchObject([{ abc: "def" }, { invalid: "property" }]); + expect({abc: "def"}).toMatchObject<{abc: string}>({abc: "def"}); + expect([{abc: 'def'}, {abc: 'def'}]).toMatchObject<[{abc: string}, {abc: string}]>([{abc: 'def'}, {abc: 'def'}]); expect({}).toMatchSnapshot(); expect({}).toMatchSnapshot("snapshotName");