From f704dbb7d66f81afda44800aa3078a67092b03f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Bu=CC=88th?= Date: Fri, 24 Jul 2020 17:21:04 +0200 Subject: [PATCH] #150: Allow any type as method stub rejections. --- src/MethodStubSetter.ts | 11 ++++------- src/ts-mockito.ts | 2 +- test/stubbing.method.spec.ts | 17 +++++++++++++++++ 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/MethodStubSetter.ts b/src/MethodStubSetter.ts index 9b0df50..5533138 100644 --- a/src/MethodStubSetter.ts +++ b/src/MethodStubSetter.ts @@ -5,7 +5,7 @@ import {ResolvePromiseMethodStub} from "./stub/ResolvePromiseMethodStub"; import {ReturnValueMethodStub} from "./stub/ReturnValueMethodStub"; import {ThrowErrorMethodStub} from "./stub/ThrowErrorMethodStub"; -export class MethodStubSetter { +export class MethodStubSetter { private static globalGroupIndex: number = 0; private groupIndex: number; @@ -47,13 +47,10 @@ export class MethodStubSetter { return this; } - public thenReject(...rest: Error[]): this { + public thenReject(...rest: RejectType[]): this { this.convertToPropertyIfIsNotAFunction(); - // Resolves undefined if no resolve values are given. - if (rest.length === 0) { - rest.push(new Error(`mocked '${this.methodToStub.name}' rejected`)); - } - rest.forEach(value => { + const rejections: any[] = rest.length === 0 ? [new Error(`mocked '${this.methodToStub.name}' rejected`)] : rest; + rejections.forEach(value => { this.methodToStub.methodStubCollection.add(new RejectPromiseMethodStub(this.groupIndex, this.methodToStub.matchers, value)); }); return this; diff --git a/src/ts-mockito.ts b/src/ts-mockito.ts index 5b37677..0d28f28 100644 --- a/src/ts-mockito.ts +++ b/src/ts-mockito.ts @@ -42,7 +42,7 @@ export function verify(method: T): MethodStubVerificator { return new MethodStubVerificator(method as any); } -export function when(method: Promise): MethodStubSetter, T, Error>; +export function when(method: Promise): MethodStubSetter, T, any>; export function when(method: T): MethodStubSetter; export function when(method: any): any { return new MethodStubSetter(method); diff --git a/test/stubbing.method.spec.ts b/test/stubbing.method.spec.ts index 038ad59..df69eb8 100644 --- a/test/stubbing.method.spec.ts +++ b/test/stubbing.method.spec.ts @@ -232,6 +232,23 @@ describe("mocking", () => { }); }); + it("rejects with given anything", done => { + // given + const sampleValue = "abc"; + const sampleRejection = "myErrorType"; + const a = when(mockedFoo.sampleMethodReturningPromise(sampleValue)); + a.thenReject(sampleRejection); + + // when + foo.sampleMethodReturningPromise(sampleValue) + .then(value => done.fail()) + .catch(err => { + // then + expect(err).toEqual(sampleRejection); + done(); + }); + }); + describe("But without defined error", () => { it("rejects with default error", done => { // given