UNPKG

2.57 kBPlain TextView Raw
1import { collectAndMergeFields } from '../src/compiler/visitors/collectAndMergeFields';
2
3import { SelectionSet } from '../src/compiler';
4
5declare global {
6 namespace jest {
7 interface Matchers<R> {
8 toMatchSelectionSet(possibleTypeNames: string[], expectedResponseKeys: string[]): R;
9 toContainSelectionSetMatching(possibleTypeNames: string[], expectedResponseKeys: string[]): R;
10 }
11 interface MatcherUtils {
12 equals(a: any, b: any): boolean;
13 }
14 }
15}
16
17function toMatchSelectionSet(
18 this: jest.MatcherUtils,
19 received: SelectionSet,
20 possibleTypeNames: string[],
21 expectedResponseKeys: string[]
22): { message(): string; pass: boolean } {
23 const actualResponseKeys = collectAndMergeFields(received).map(field => field.responseKey);
24
25 const pass = this.equals(actualResponseKeys, expectedResponseKeys);
26
27 if (pass) {
28 return {
29 message: () =>
30 `Expected selection set for ${this.utils.printExpected(possibleTypeNames)}\n` +
31 `To not match:\n` +
32 ` ${this.utils.printExpected(expectedResponseKeys)}` +
33 'Received:\n' +
34 ` ${this.utils.printReceived(actualResponseKeys)}`,
35 pass: true
36 };
37 } else {
38 return {
39 message: () =>
40 `Expected selection set for ${this.utils.printExpected(possibleTypeNames)}\n` +
41 `To match:\n` +
42 ` ${this.utils.printExpected(expectedResponseKeys)}\n` +
43 'Received:\n' +
44 ` ${this.utils.printReceived(actualResponseKeys)}`,
45 pass: false
46 };
47 }
48}
49
50function toContainSelectionSetMatching(
51 this: jest.MatcherUtils,
52 received: SelectionSet[],
53 possibleTypeNames: string[],
54 expectedResponseKeys: string[]
55): { message(): string; pass: boolean } {
56 const variant = received.find(variant => {
57 return this.equals(Array.from(variant.possibleTypes).map(type => type.name), possibleTypeNames);
58 });
59
60 if (!variant) {
61 return {
62 message: () =>
63 `Expected array to contain variant for:\n` +
64 ` ${this.utils.printExpected(possibleTypeNames)}\n` +
65 `But only found variants for:\n` +
66 received
67 .map(
68 variant =>
69 ` ${this.utils.printReceived(variant.possibleTypes)} -> ${this.utils.printReceived(
70 collectAndMergeFields(variant).map(field => field.name)
71 )}`
72 )
73 .join('\n'),
74 pass: false
75 };
76 }
77
78 return toMatchSelectionSet.call(this, variant, possibleTypeNames, expectedResponseKeys);
79}
80
81expect.extend({
82 toMatchSelectionSet,
83 toContainSelectionSetMatching
84} as any);