Skip to content

Commit 7a7a778

Browse files
jerelmillerphryneasbenjamn
authored
Custom document transforms (#10509)
Co-authored-by: Lenz Weber-Tronic <[email protected]> Co-authored-by: Ben Newman <[email protected]>
0 parents  commit 7a7a778

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

src/testing/matchers/index.d.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import type { DocumentNode } from '../../core';
2+
3+
interface ApolloCustomMatchers<R = void> {
4+
/**
5+
* Used to determine if two GraphQL query documents are equal to each other by
6+
* comparing their printed values. The document must be parsed by `gql`.
7+
*/
8+
toMatchDocument(document: DocumentNode): R;
9+
}
10+
11+
declare global {
12+
namespace jest {
13+
interface Matchers<R = void> extends ApolloCustomMatchers<R> {}
14+
}
15+
}

src/testing/matchers/index.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { expect } from '@jest/globals';
2+
import { toMatchDocument } from './toMatchDocument';
3+
4+
expect.extend({
5+
toMatchDocument,
6+
});
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { checkDocument } from '../../utilities';
2+
import { print } from 'graphql';
3+
import type { DocumentNode } from '../../core';
4+
import type { MatcherFunction } from 'expect';
5+
6+
export const toMatchDocument: MatcherFunction<[document: DocumentNode]> =
7+
function (actual, document) {
8+
const hint = this.utils.matcherHint('toMatchDocument');
9+
const actualDocument = print(
10+
validateDocument(
11+
actual,
12+
hint +
13+
`\n\n${this.utils.RECEIVED_COLOR(
14+
'received'
15+
)} document must be a parsed document.`
16+
)
17+
);
18+
const expectedDocument = print(
19+
validateDocument(
20+
document,
21+
hint +
22+
`\n\n${this.utils.EXPECTED_COLOR(
23+
'expected'
24+
)} document must be a parsed document.`
25+
)
26+
);
27+
28+
const pass = actualDocument === expectedDocument;
29+
30+
return {
31+
pass,
32+
message: () => {
33+
const hint = this.utils.matcherHint(
34+
'toMatchDocument',
35+
undefined,
36+
undefined,
37+
{ isNot: this.isNot }
38+
);
39+
40+
if (pass) {
41+
return (
42+
hint +
43+
'\n\n' +
44+
'Received:\n\n' +
45+
this.utils.RECEIVED_COLOR(actualDocument)
46+
);
47+
}
48+
49+
return (
50+
hint + '\n\n' + this.utils.diff(expectedDocument, actualDocument)
51+
);
52+
},
53+
};
54+
};
55+
56+
function validateDocument(document: unknown, message: string) {
57+
try {
58+
checkDocument(document as DocumentNode);
59+
} catch (e) {
60+
throw new Error(message);
61+
}
62+
63+
return document as DocumentNode;
64+
}

0 commit comments

Comments
 (0)