-
Notifications
You must be signed in to change notification settings - Fork 242
/
toMatchAST.ts
64 lines (58 loc) 路 1.6 KB
/
toMatchAST.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
import { print, ASTNode } from 'graphql';
const diff = require('jest-diff');
declare global {
namespace jest {
interface Matchers<R, T> {
toMatchAST(expected: ASTNode): R;
}
}
}
const lineEndRegex = /^/gm;
function indentString(string: string, count = 2) {
if (!string) return string;
return string.replace(lineEndRegex, ' '.repeat(count));
}
function toMatchAST(
this: jest.MatcherUtils,
received: ASTNode,
expected: ASTNode,
): { message(): string; pass: boolean } {
const receivedString = print(received);
const expectedString = print(expected);
const printReceived = (string: string) =>
this.utils.RECEIVED_COLOR(indentString(string));
const printExpected = (string: string) =>
this.utils.EXPECTED_COLOR(indentString(string));
const pass = this.equals(receivedString, expectedString);
const message = pass
? () =>
this.utils.matcherHint('.not.toMatchAST') +
'\n\n' +
`Expected AST to not equal:\n` +
printExpected(expectedString) +
'\n' +
`Received:\n` +
printReceived(receivedString)
: () => {
const diffString = diff(expectedString, receivedString, {
expand: this.expand,
});
return (
this.utils.matcherHint('.toMatchAST') +
'\n\n' +
`Expected AST to equal:\n` +
printExpected(expectedString) +
'\n' +
`Received:\n` +
printReceived(receivedString) +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
);
};
return {
message,
pass,
};
}
expect.extend({
toMatchAST,
});