forked from apollographql/apollo-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtests.js
376 lines (317 loc) · 10.9 KB
/
tests.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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
const assert = require("assert");
const {
ApolloClient,
InMemoryCache,
gql,
makeVar,
} = require("@apollo/client/core");
function itAsync(message, testFn) {
const start = Date.now();
let timeout;
(function pollGC() {
gc(); // enabled by --expose-gc
// Passing --exit to mocha should cause the process to exit after
// tests pass/fail/timeout, but (in case that fails) we also set a
// hard limit of 10 seconds for GC polling.
if (Date.now() < start + 10000) {
timeout = setTimeout(pollGC, 100);
}
})();
return it(message, () => new Promise(testFn).finally(() => {
clearTimeout(timeout);
}));
}
const registries = [];
function makeRegistry(callback, reject) {
assert.strictEqual(typeof callback, "function");
assert.strictEqual(typeof reject, "function");
const registry = new FinalizationRegistry(key => {
try {
callback(key);
} catch (error) {
// Exceptions thrown in FinalizationRegistry callbacks can be tricky
// for test frameworks to catch, without some help.
reject(error);
}
});
// If the registry object itself gets garbage collected before the
// callback fires, the callback might never be called:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks
registries.push(registry);
return registry;
}
// This is not technically a memory-related test, but it depends on the build
// artifacts generated in the ../../dist directory by `npm run build`, which is
// an assumption shared by the other tests in this file.
describe("@apollo/client/apollo-client.cjs", () => {
it("can be imported as a single CommonJS bundle (issue #8592)", () => {
const bundle = require("@apollo/client/apollo-client.cjs");
// Very basic test that requiring the bundle worked.
assert.strictEqual(typeof bundle.ApolloClient, "function");
assert.strictEqual(typeof bundle.InMemoryCache, "function");
// TODO This will change in AC4 when we move all React exports to the
// @apollo/client/react entry point (see issue #8190).
assert.strictEqual(typeof bundle.ApolloProvider, "function");
// The CommonJS bundles referred to by the "main" fields in the various
// package.json files that we generate during `npm run build` are all
// independent, non-overlapping bundles, but apollo-client.cjs is its own
// bundle, so importing it duplicates everything.
assert.notStrictEqual(bundle.ApolloClient, ApolloClient);
assert.notStrictEqual(bundle.InMemoryCache, InMemoryCache);
});
});
describe("garbage collection", () => {
itAsync("should collect client.cache after client.stop()", (resolve, reject) => {
const expectedKeys = new Set([
"client.cache",
"ObservableQuery",
]);
const registry = makeRegistry(key => {
if (expectedKeys.delete(key) && !expectedKeys.size) {
resolve();
}
}, reject);
const localVar = makeVar(123);
(function (client) {
registry.register(client.cache, "client.cache");
const obsQuery = client.watchQuery({
query: gql`query { local }`,
});
registry.register(obsQuery, "ObservableQuery");
obsQuery.subscribe({
next(result) {
assert.deepStrictEqual(result.data, {
local: 123,
});
client.stop();
},
});
})(new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
local() {
return localVar();
},
},
},
},
}),
}));
});
itAsync("should release cache.storeReader if requested via cache.gc", (resolve, reject) => {
const expectedKeys = {
__proto__: null,
StoreReader1: true,
ObjectCanon1: true,
StoreReader2: true,
ObjectCanon2: true,
StoreReader3: false,
ObjectCanon3: false,
};
const registry = makeRegistry(key => {
// Referring to client here should keep the client itself alive
// until after the ObservableQuery is (or should have been)
// collected. Collecting the ObservableQuery just because the whole
// client instance was collected is not interesting.
assert.strictEqual(client instanceof ApolloClient, true);
if (key in expectedKeys) {
assert.strictEqual(expectedKeys[key], true, key);
}
delete expectedKeys[key];
if (Object.keys(expectedKeys).every(key => !expectedKeys[key])) {
setTimeout(resolve, 100);
}
}, reject);
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
local() {
return "hello";
},
},
},
},
// Explicitly disable canonization to test that it can be overridden.
canonizeResults: false,
});
const client = new ApolloClient({ cache });
(function () {
const query = gql`query { local }`;
const obsQuery = client.watchQuery({
query,
canonizeResults: true,
});
function register(suffix) {
const reader = cache["storeReader"];
registry.register(reader, "StoreReader" + suffix);
registry.register(reader.canon, "ObjectCanon" + suffix);
}
register(1);
const sub = obsQuery.subscribe({
next(result) {
assert.deepStrictEqual(result.data, {
local: "hello",
});
const read = () => cache.readQuery({
query,
canonizeResults: true,
});
assert.strictEqual(read(), result.data);
assert.deepStrictEqual(cache.gc(), []);
// Nothing changes because we merely called cache.gc().
assert.strictEqual(
read(),
result.data,
);
assert.deepStrictEqual(cache.gc({
// Now reset the result cache but preserve reader.canon, so the
// results will be === even though they have to be recomputed.
resetResultCache: true,
resetResultIdentities: false,
}), []);
register(2);
const dataAfterResetWithSameCanon = read();
assert.strictEqual(dataAfterResetWithSameCanon, result.data);
assert.deepStrictEqual(cache.gc({
// Finally, do a full reset of the result caching system, including
// discarding reader.canon, so === result identity is lost.
resetResultCache: true,
resetResultIdentities: true,
}), []);
register(3);
const dataAfterFullReset = read();
assert.notStrictEqual(dataAfterFullReset, result.data);
assert.deepStrictEqual(dataAfterFullReset, result.data);
sub.unsubscribe();
},
});
})();
});
itAsync("should collect ObservableQuery after tear-down", (resolve, reject) => {
const expectedKeys = new Set([
"ObservableQuery",
]);
const registry = makeRegistry(key => {
// Referring to client here should keep the client itself alive
// until after the ObservableQuery is (or should have been)
// collected. Collecting the ObservableQuery just because the whole
// client instance was collected is not interesting.
assert.strictEqual(client instanceof ApolloClient, true);
if (expectedKeys.delete(key) && !expectedKeys.size) {
resolve();
}
}, reject);
const localVar = makeVar(123);
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
local() {
return localVar();
},
},
},
},
}),
});
(function () {
const obsQuery = client.watchQuery({
query: gql`query { local }`,
});
registry.register(obsQuery, "ObservableQuery");
const sub = obsQuery.subscribe({
next(result) {
assert.deepStrictEqual(result.data, {
local: 123,
});
sub.unsubscribe();
},
});
})();
});
itAsync("getMarkupFromTree and RenderPromises", (resolve, reject) => {
const {
createElement,
} = require("react");
assert.strictEqual(typeof createElement, "function");
const {
useQuery,
useApolloClient,
getApolloContext,
} = require("@apollo/client/react");
assert.strictEqual(typeof useQuery, "function");
assert.strictEqual(typeof useApolloClient, "function");
assert.strictEqual(typeof getApolloContext, "function");
const {
getDataFromTree,
RenderPromises,
} = require("@apollo/client/react/ssr");
assert.strictEqual(typeof getDataFromTree, "function");
const expectedKeys = new Set(["cache", "queryInfo1"]);
const renderPromisesSet = new Set;
const registry = makeRegistry(key => {
// By retaining the RenderPromises object in a Set in the scope of
// this callback function, we artificially ensure the RenderPromises
// won't be garbage collected before this function runs, so we can
// verify that renderPromises.clear() was called by getDataFromTree.
assert.strictEqual(renderPromisesSet.size, 1);
renderPromisesSet.forEach(rp => {
assert.strictEqual(rp.stopped, true);
});
if (expectedKeys.delete(key) && !expectedKeys.size) {
resolve();
}
}, reject);
const query = gql`query { __typename }`;
function Component() {
const client = useApolloClient();
assert.strictEqual(client instanceof ApolloClient, true);
const { loading, data } = useQuery(query, {
fetchPolicy: "cache-only",
});
if (loading || !data) {
return "loading...";
}
registry.register(client.cache, "cache");
// Register any/all watched ObservableQuery objects with the registry.
client.queryManager.queries.forEach((queryInfo, queryId) => {
registry.register(queryInfo, "queryInfo" + queryId);
});
const ApolloContext = getApolloContext();
return createElement(
ApolloContext.Consumer,
null,
context => {
assert.ok(
context.renderPromises instanceof RenderPromises,
context.renderPromises,
);
// This keeps the RenderPromises object alive artificially so we can
// verify that it is properly cleared.
renderPromisesSet.add(context.renderPromises);
return createElement("code", null, JSON.stringify(data));
},
);
}
const tree = createElement(Component);
(function () {
const client = new ApolloClient({
cache: new InMemoryCache,
ssrMode: true,
});
getDataFromTree(tree, {
client,
}).then(html => {
assert.strictEqual(
html,
'<code>{"__typename":"Query"}</code>',
);
client.stop();
}).catch(reject);
})();
});
});