-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcustomMatchers.ts
65 lines (54 loc) · 2.9 KB
/
customMatchers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { ApplicationError, EventConstructor, Result } from "@js-soft/ts-utils";
import { MockEventBus } from "./lib";
import "./lib/MockUIBridge.matchers";
expect.extend({
toBeSuccessful(actual: Result<unknown, ApplicationError>) {
if (!(actual instanceof Result)) {
return { pass: false, message: () => "expected an instance of Result." };
}
return { pass: actual.isSuccess, message: () => `expected a successful result; got an error result with the error message '${actual.error.message}'.` };
},
toBeAnError(actual: Result<unknown, ApplicationError>, expectedMessage: string | RegExp, expectedCode: string | RegExp) {
if (!(actual instanceof Result)) {
return { pass: false, message: () => "expected an instance of Result." };
}
if (!actual.isError) {
return { pass: false, message: () => "expected an error result, but it was successful." };
}
if (actual.error.message.match(new RegExp(expectedMessage)) === null) {
return { pass: false, message: () => `expected the error message of the result to match '${expectedMessage}', but received '${actual.error.message}'.` };
}
if (actual.error.code.match(new RegExp(expectedCode)) === null) {
return { pass: false, message: () => `expected the error code of the result to match '${expectedCode}', but received '${actual.error.code}'.` };
}
return { pass: true, message: () => "" };
},
async toHavePublished<TEvent>(eventBus: unknown, eventConstructor: EventConstructor<TEvent>, eventConditions?: (event: TEvent) => boolean) {
if (!(eventBus instanceof MockEventBus)) {
throw new Error("This method can only be used with expect(MockEventBus).");
}
await eventBus.waitForRunningEventHandlers();
const matchingEvents = eventBus.publishedEvents.filter((x) => x instanceof eventConstructor && (eventConditions?.(x) ?? true));
if (matchingEvents.length > 0) {
return {
pass: true,
message: () =>
`There were one or more events that matched the specified criteria, even though there should be none. The matching events are: ${JSON.stringify(
matchingEvents,
undefined,
2
)}`
};
}
return { pass: false, message: () => `The expected event wasn't published. The published events are: ${JSON.stringify(eventBus.publishedEvents, undefined, 2)}` };
}
});
declare global {
namespace jest {
interface Matchers<R> {
toBeSuccessful(): R;
toBeAnError(expectedMessage: string | RegExp, expectedCode: string | RegExp): R;
toHavePublished<TEvent>(eventConstructor: EventConstructor<TEvent>, eventConditions?: (event: TEvent) => boolean): Promise<R>;
}
}
}