/
mocks.ts
352 lines (322 loc) · 10.6 KB
/
mocks.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
import {
Kind,
type DocumentNode,
OperationTypeNode,
GraphQLError,
type DefinitionNode,
type FieldNode,
type OperationDefinitionNode,
type TypeNode,
type SelectionNode,
type FragmentDefinitionNode,
} from 'graphql'
import { waitForNextTick } from '#tests/support/utils.ts'
import {
ApolloClient,
ApolloLink,
Observable,
type FetchResult,
type Operation,
} from '@apollo/client/core'
import {
cloneDeep,
mergeDeep,
removeConnectionDirectiveFromDocument,
} from '@apollo/client/utilities'
import { visit, print } from 'graphql'
import createCache from '#shared/server/apollo/cache.ts'
import type { CacheInitializerModules } from '#shared/types/server/apollo/client.ts'
import { noop } from 'lodash-es'
import { provideApolloClient } from '@vue/apollo-composable'
import type { DeepPartial, DeepRequired } from '#shared/types/utils.ts'
import {
getFieldData,
getObjectDefinition,
getOperationDefinition,
mockOperation,
} from './index.ts'
interface MockCall<T = any> {
document: DocumentNode
result: T
variables: Record<string, any>
}
const mockDefaults = new Map<string, any>()
const mockResults = new Map<string, any>()
const mockCalls = new Map<string, MockCall[]>()
const queryStrings = new WeakMap<DocumentNode, string>()
const stripNames = (query: DocumentNode) => {
return visit(query, {
Field: {
enter(node) {
return node.name.value === '__typename' ? null : undefined
},
},
})
}
const normalize = (query: DocumentNode) => {
const directiveless = removeConnectionDirectiveFromDocument(query)
const stripped = directiveless !== null ? stripNames(directiveless) : null
return stripped === null ? query : stripped
}
const requestToKey = (query: DocumentNode) => {
const cached = queryStrings.get(query)
if (cached) return cached
const normalized = normalize(query)
const queryString = query && print(normalized)
const stringified = JSON.stringify({ query: queryString })
queryStrings.set(query, stringified)
return stringified
}
const stripQueryData = (
definition: DefinitionNode | FieldNode,
fragments: FragmentDefinitionNode[],
resultData: any,
newData: any = {},
// eslint-disable-next-line sonarjs/cognitive-complexity
) => {
if (!('selectionSet' in definition) || !definition.selectionSet) {
return newData
}
if (typeof newData !== 'object' || newData === null) {
return newData
}
if (typeof newData !== 'object' || resultData === null) {
return resultData
}
const name = definition.name!.value
const processNode = (node: SelectionNode) => {
if (node.kind === Kind.INLINE_FRAGMENT) {
const condition = node.typeCondition
if (!condition || condition.kind !== Kind.NAMED_TYPE) {
throw new Error('Unknown type condition!')
}
const typename = condition.name.value
if (resultData.__typename === typename) {
node.selectionSet.selections.forEach(processNode)
}
return
}
if (node.kind === Kind.FRAGMENT_SPREAD) {
const fragment = fragments.find(
(fragment) => fragment.name.value === node.name.value,
)
if (fragment) {
fragment.selectionSet.selections.forEach(processNode)
}
return
}
const fieldName =
'alias' in node && node.alias ? node.alias?.value : node.name!.value
if (!fieldName) {
return
}
const resultValue = resultData[fieldName]
if ('selectionSet' in node && node.selectionSet) {
if (Array.isArray(resultValue)) {
newData[fieldName] = resultValue.map((item) =>
stripQueryData(node, fragments, item, newData[name]),
)
} else {
newData[fieldName] = stripQueryData(
node,
fragments,
resultValue,
newData[name],
)
}
} else {
newData[fieldName] = resultValue
}
}
definition.selectionSet?.selections.forEach(processNode)
return newData
}
// Returns the full query result, not the object that was returned in the operation
// So, if you didn't ask for a field, but it's defined in the type schema, this field WILL be in the object
export const getGraphQLResult = <T>(
document: DocumentNode,
): { data: DeepRequired<T> } => {
return mockResults.get(requestToKey(document))
}
export const getGraphQLMockCalls = <T>(
document: DocumentNode,
): MockCall<DeepRequired<T>>[] => {
return mockCalls.get(requestToKey(document)) || []
}
export const waitForGraphQLMockCalls = async <T>(
document: DocumentNode,
): Promise<MockCall<DeepRequired<T>>[]> => {
return vi.waitUntil(() => getGraphQLMockCalls<T>(document))
}
export const mockGraphQLResult = <T extends Record<string, any>>(
document: DocumentNode,
defaults:
| DeepPartial<T>
| ((variables?: Record<string, unknown>) => DeepPartial<T>),
) => {
const key = requestToKey(document)
mockDefaults.set(key, defaults)
return {
getResult: () => getGraphQLResult<T>(document),
updateDefaults: (defaults: DeepPartial<T>) => {
mockDefaults.set(key, defaults)
},
waitForCalls: () => waitForGraphQLMockCalls<T>(document),
}
}
export const waitForGraphQLResult = async <T>(document: DocumentNode) => {
return vi.waitUntil(() => getGraphQLResult<T>(document))
}
export interface TestSubscriptionHandler<T extends Record<string, any> = any> {
/** Ensure that some data will be returned based on the schema */
trigger(defaults?: DeepPartial<T>): Promise<T>
triggerErrors(errors: GraphQLError[]): Promise<void>
error(values?: unknown): void
complete(): void
closed(): boolean
}
const mockSubscriptionHanlders = new Map<
string,
TestSubscriptionHandler<Record<string, any>>
>()
export const getGraphQLSubscriptionHandler = <T extends Record<string, any>>(
document: DocumentNode,
) => {
return mockSubscriptionHanlders.get(
requestToKey(document),
) as TestSubscriptionHandler<T>
}
afterEach(() => {
mockCalls.clear()
mockResults.clear()
mockSubscriptionHanlders.clear()
mockDefaults.clear()
mockCalls.clear()
})
const getInputObjectType = (variableNode: TypeNode): string | null => {
if (variableNode.kind === Kind.NON_NULL_TYPE) {
return getInputObjectType(variableNode.type)
}
if (variableNode.kind === Kind.LIST_TYPE) {
return null
}
return variableNode.name.value
}
// assume "$input" value is the default, but test defaults will take precedence
const getQueryDefaults = (
requestKey: string,
definition: OperationDefinitionNode,
variables: Record<string, any>,
): Record<string, any> => {
let userDefaults = mockDefaults.get(requestKey)
if (typeof userDefaults === 'function') {
userDefaults = userDefaults(variables)
}
if (!variables.input || definition.operation !== OperationTypeNode.MUTATION)
return userDefaults
const inputVariableNode = definition.variableDefinitions?.find((node) => {
return node.variable.name.value === 'input'
})
if (!inputVariableNode) return userDefaults
const objectInputType = getInputObjectType(inputVariableNode.type)
if (!objectInputType || !objectInputType.endsWith('Input'))
return userDefaults
const objectType = objectInputType.slice(0, -5)
const mutationName = definition.name!.value
const mutationDefinition = getOperationDefinition(
definition.operation,
mutationName,
)
// expect object to be in the first level, otherwise we might update the wrong object
const payloadDefinition = getObjectDefinition(mutationDefinition.type.name)
const sameTypeField = payloadDefinition.fields?.find((node) => {
return getFieldData(node.type).name === objectType
})
if (!sameTypeField) return userDefaults
const inputDefaults = {
[mutationName]: {
[sameTypeField.name]: variables.input,
},
}
return mergeDeep(inputDefaults, userDefaults || {})
}
// This link automatically:
// - respects "$typeId" variables, doesn't respect "$typeInternalId" because we need to move away from them
// - mocks queries, respects defaults
// - mocks mutations, respects defaults, but also looks for "$input" variable and updates the object if it's inside the first level
// - mocks result for subscriptions, respects defaults
class MockLink extends ApolloLink {
// eslint-disable-next-line class-methods-use-this
request(operation: Operation): Observable<FetchResult> | null {
const { query, variables } = operation
const definition = query.definitions[0]
if (definition.kind !== Kind.OPERATION_DEFINITION) {
return null
}
const fragments = query.definitions.filter(
(def) => def.kind === Kind.FRAGMENT_DEFINITION,
) as FragmentDefinitionNode[]
const queryKey = requestToKey(query)
return new Observable((observer) => {
const { operation } = definition
if (operation === OperationTypeNode.SUBSCRIPTION) {
const handler: TestSubscriptionHandler = {
async trigger(defaults) {
const resultValue = mockOperation(query, variables, defaults)
const data = stripQueryData(definition, fragments, resultValue)
observer.next({ data })
await waitForNextTick(true)
return resultValue
},
async triggerErrors(errors) {
observer.next({ errors })
await waitForNextTick(true)
},
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
closed: () => observer.closed,
}
mockSubscriptionHanlders.set(queryKey, handler)
return noop
}
try {
const defaults = getQueryDefaults(queryKey, definition, variables)
const returnResult = mockOperation(query, variables, defaults)
const result = { data: returnResult }
mockResults.set(queryKey, result)
const calls = mockCalls.get(queryKey) || []
calls.push({ document: query, result: result.data, variables })
mockCalls.set(queryKey, calls)
observer.next(
cloneDeep({
data: stripQueryData(definition, fragments, result.data),
}),
)
observer.complete()
} catch (e) {
console.error(e)
throw e
}
return noop
})
}
}
const cacheInitializerModules: CacheInitializerModules = import.meta.glob(
'../../../../mobile/server/apollo/cache/initializer/*.ts',
{ eager: true },
)
const createMockClient = () => {
const link = new MockLink()
const cache = createCache(cacheInitializerModules)
const client = new ApolloClient({
cache,
link,
})
provideApolloClient(client)
return client
}
export const mockedApolloClient = createMockClient()
afterEach(() => {
mockedApolloClient.clearStore()
})