/
handleErrors.js
90 lines (82 loc) · 2.61 KB
/
handleErrors.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// @flow strict
import printDiff from 'jest-diff';
import type { MockGraphQLConfig } from './index';
import { QueryMock } from './index';
import type { Variables } from './types';
export function printNoMockFoundError(
queryMock: QueryMock,
operationName: string,
variables: Variables
): void {
const errorMessageArray = getNoMockFoundErrorMessageArray(
queryMock,
operationName,
variables
);
throw new Error(errorMessageArray.join(''));
}
function getNoMockFoundErrorMessageArray(
queryMock: QueryMock,
operationName: string,
variables: Variables
): Array<string> {
const mockedQueriesMessageArray = [
`Could not find matching mock for operation "${operationName}" ` +
`with variables: ${JSON.stringify(variables)}\n` +
`Make sure you have mocked the query you are making.\n\n`
];
if (!Object.entries(queryMock._queries).length) {
mockedQueriesMessageArray.push(`=== No query was mocked ===\n\n`);
return mockedQueriesMessageArray;
}
if (queryMock._queries[operationName]) {
mockedQueriesMessageArray.push(
`=== Currently mocked "${operationName}" queries ===\n`
);
queryMock._queries[operationName].forEach(({ queryMockConfig }) => {
mockedQueriesMessageArray.push(
`Query "variables": ${JSON.stringify(queryMockConfig.variables) ||
'-'}\n` +
`Diff of "variables":\n` +
`${printDiff(queryMockConfig.variables, variables)}\n\n`
);
});
}
const otherMockedQueryNames = Object.keys(queryMock._queries).filter(
queryMockName => operationName !== queryMockName
);
if (!otherMockedQueryNames.length) {
return mockedQueriesMessageArray;
}
mockedQueriesMessageArray.push(
`=== ${
queryMock._queries[operationName] ? 'Other' : 'All'
} mocked queries ===\n`
);
otherMockedQueryNames.forEach(queryName => {
mockedQueriesMessageArray.push(`- "${queryName || 'unknown'}"\n`);
});
mockedQueriesMessageArray.push(`\n`);
return mockedQueriesMessageArray;
}
export function printVariablesDoesNotMatchError(
queryMockConfig: MockGraphQLConfig,
shouldMatchOnVariables: boolean,
operationName: string,
variables: Variables
): void {
if (shouldMatchOnVariables) {
let errorStr = `Variables do not match for operation "${operationName ||
'unknown'}"`;
if (queryMockConfig.matchVariables) {
throw new Error(`${errorStr} due to custom "matchOnVariables" function`);
} else {
throw new Error(
`${errorStr}.\n\nVariables in request VS mocked variables: \n${printDiff(
variables,
queryMockConfig.variables
)}`
);
}
}
}