Skip to content

Commit

Permalink
NagRock#150: Allow any type as method stub rejections.
Browse files Browse the repository at this point in the history
  • Loading branch information
cornr committed Jul 24, 2020
1 parent 6637048 commit f704dbb
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 8 deletions.
11 changes: 4 additions & 7 deletions src/MethodStubSetter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {ResolvePromiseMethodStub} from "./stub/ResolvePromiseMethodStub";
import {ReturnValueMethodStub} from "./stub/ReturnValueMethodStub";
import {ThrowErrorMethodStub} from "./stub/ThrowErrorMethodStub";

export class MethodStubSetter<T, ResolveType = void, RejectType = Error> {
export class MethodStubSetter<T, ResolveType = void, RejectType = any> {
private static globalGroupIndex: number = 0;
private groupIndex: number;

Expand Down Expand Up @@ -47,13 +47,10 @@ export class MethodStubSetter<T, ResolveType = void, RejectType = Error> {
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;
Expand Down
2 changes: 1 addition & 1 deletion src/ts-mockito.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export function verify<T>(method: T): MethodStubVerificator<T> {
return new MethodStubVerificator(method as any);
}

export function when<T>(method: Promise<T>): MethodStubSetter<Promise<T>, T, Error>;
export function when<T>(method: Promise<T>): MethodStubSetter<Promise<T>, T, any>;
export function when<T>(method: T): MethodStubSetter<T>;
export function when<T>(method: any): any {
return new MethodStubSetter(method);
Expand Down
17 changes: 17 additions & 0 deletions test/stubbing.method.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit f704dbb

Please sign in to comment.