NagRock / ts-mockito

Mocking library for TypeScript
MIT License
974 stars 93 forks source link

Can I make a custom matcher? #184

Closed AnthonyIacono closed 4 years ago

AnthonyIacono commented 4 years ago

First of all, thank you so much for this wonderful tool! Is there a way to make a custom matcher?

ie:

when(something.whatever(matches(v => v.boop === "cheese")))
        .thenResolve("meow");

const instance = instance(something);

await instance.whatever({boop: "cheese", "foo": "bar"});
gCardinal commented 4 years ago

Can't say I tried it, but custom matchers seem to be possible. You can look here for how matchers are implemented, you'd need to pass an object with a match property that is a function, taking in a value and returning a boolean.

const cheeseMatcher = {match: (value: any) => value.boop === 'cheese'}
when(something.whatever(cheeseMatcher)).thenResolve('meow')

The cleaner way might probably be to implement the matcher in a class and then expose the matcher method like so:

export function cheeseMatcher(): any {
    return new CheeseMatcher() as any;
}

References: Matcher: https://github.com/NagRock/ts-mockito/blob/master/src/matcher/type/AnyNumberMatcher.ts Exposing matcher method: https://github.com/NagRock/ts-mockito/blob/master/src/ts-mockito.ts#L112

NagRock commented 4 years ago

Thanks @gCardinal for posting solution.