From 17a24edb012e06c05dac9158b7d5266df667ef95 Mon Sep 17 00:00:00 2001 From: antoinebrault Date: Tue, 12 Feb 2019 17:06:30 -0500 Subject: [PATCH] [jest] add mock result type --- types/jest/index.d.ts | 31 ++++++++++++++++++++----------- types/jest/jest-tests.ts | 13 +++++++++++++ 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 526beb2dc7..a09263369e 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -976,20 +976,29 @@ declare namespace jest { } /** - * Represents the result of a single call to a mock function. + * Represents the result of a single call to a mock function with a return value. */ - interface MockResult { - /** - * True if the function threw. - * False if the function returned. - */ - isThrow: boolean; - /** - * The value that was either thrown or returned by the function. - */ + interface MockResultReturn { + type: 'return'; + value: T; + } + /** + * Represents the result of a single incomplete call to a mock function. + */ + interface MockResultIncomplete { + type: 'incomplete'; + value: undefined; + } + /** + * Represents the result of a single call to a mock function with a thrown error. + */ + interface MockResultThrow { + type: 'throw'; value: any; } + type MockResult = MockResultReturn | MockResultThrow | MockResultIncomplete; + interface MockContext { calls: Y[]; instances: T[]; @@ -997,7 +1006,7 @@ declare namespace jest { /** * List of results of calls to the mock function. */ - results: MockResult[]; + results: Array>; } } diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index c643ca6a57..3ac82cda9d 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -480,6 +480,19 @@ mocked.test4.mockRejectedValue(new Error()); // $ExpectError mocked.test4.mockRejectedValueOnce(new Error()); +const mockResult = jest.fn(() => 1).mock.results[0]; +switch (mockResult.type) { + case 'return': + mockResult.value; // $ExpectType number + break; + case 'incomplete': + mockResult.value; // $ExpectType undefined + break; + case 'throw': + mockResult.value; // $ExpectType any + break; +} + /* Snapshot serialization */ const snapshotSerializerPlugin: jest.SnapshotSerializerPlugin = {