-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathLDClientImpl.start.test.ts
More file actions
315 lines (256 loc) · 10.6 KB
/
LDClientImpl.start.test.ts
File metadata and controls
315 lines (256 loc) · 10.6 KB
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
import { AutoEnvAttributes, clone, Hasher, LDLogger } from '@launchdarkly/js-sdk-common';
import { LDContext } from '../src/api/LDContext';
import * as bootstrapModule from '../src/flag-manager/bootstrap';
import LDClientImpl from '../src/LDClientImpl';
import { Flags } from '../src/types';
import { createBasicPlatform } from './createBasicPlatform';
import * as mockResponseJson from './evaluation/mockResponse.json';
import { goodBootstrapData, goodBootstrapDataWithReasons } from './flag-manager/testBootstrapData';
import { MockEventSource } from './streaming/LDClientImpl.mocks';
import { makeTestDataManagerFactory } from './TestDataManager';
const testSdkKey = 'test-sdk-key';
const context: LDContext = { kind: 'user', key: 'test-user' };
let clients: LDClientImpl[] = [];
function setupClient(
mockPlatform: ReturnType<typeof createBasicPlatform>,
options?: {
logger?: LDLogger;
requiresStart?: boolean;
disableNetwork?: boolean;
sendEvents?: boolean;
initialContext?: LDContext;
},
) {
const logger = options?.logger ?? {
error: jest.fn(),
warn: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
};
const ldc = new LDClientImpl(
testSdkKey,
AutoEnvAttributes.Disabled,
mockPlatform,
{
logger,
sendEvents: options?.sendEvents ?? false,
},
makeTestDataManagerFactory(testSdkKey, mockPlatform, {
disableNetwork: options?.disableNetwork,
}),
{
getImplementationHooks: () => [],
credentialType: 'clientSideId',
requiresStart: options?.requiresStart ?? true,
initialContext: options?.initialContext,
},
);
clients.push(ldc);
return { ldc, logger };
}
function setupStreamingPlatform() {
const mockPlatform = createBasicPlatform();
const defaultPutResponse = clone<Flags>(mockResponseJson);
mockPlatform.crypto.randomUUID.mockReturnValue('random1');
const hasher = {
update: jest.fn((): Hasher => hasher),
digest: jest.fn(() => 'digested1'),
};
mockPlatform.crypto.createHash.mockReturnValue(hasher);
mockPlatform.requests.getEventSourceCapabilities.mockImplementation(() => ({
readTimeout: true,
headers: true,
customMethod: true,
}));
mockPlatform.requests.createEventSource.mockImplementation(
(streamUri: string = '', options: any = {}) => {
const mockEventSource = new MockEventSource(streamUri, options);
mockEventSource.simulateEvents('put', [{ data: JSON.stringify(defaultPutResponse) }]);
return mockEventSource;
},
);
return mockPlatform;
}
describe('LDClientImpl.start()', () => {
afterEach(async () => {
await Promise.all(clients.map((c) => c.close()));
clients = [];
jest.resetAllMocks();
});
it('returns failed status when initial context is not set', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform);
const result = await ldc.start();
expect(result).toEqual({
status: 'failed',
error: expect.any(Error),
});
});
it('returns the same promise when called multiple times', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { initialContext: context });
const promise1 = ldc.start();
const promise2 = ldc.start();
const promise3 = ldc.start();
expect(promise1).toBe(promise2);
expect(promise2).toBe(promise3);
const [result1, result2, result3] = await Promise.all([promise1, promise2, promise3]);
expect(result1).toEqual(result2);
expect(result2).toEqual(result3);
expect(result1.status).toBe('complete');
});
it('returns cached result after initialization completes', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { initialContext: context });
const result1 = await ldc.start();
expect(result1.status).toBe('complete');
const result2 = await ldc.start();
expect(result2.status).toBe('complete');
});
it('resolves with complete status on successful identify', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { initialContext: context });
const result = await ldc.start();
expect(result.status).toBe('complete');
});
it('sets the active context after start completes', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { initialContext: context });
expect(ldc.getContext()).toBeUndefined();
await ldc.start();
expect(ldc.getContext()).toEqual(context);
});
describe('bootstrap data', () => {
it('presets flags from bootstrap in identifyOptions', async () => {
const mockPlatform = createBasicPlatform();
const { ldc } = setupClient(mockPlatform, { disableNetwork: true, initialContext: context });
await ldc.start({
identifyOptions: { bootstrap: goodBootstrapData },
});
const flags = ldc.allFlags();
expect(flags.killswitch).toBe(true);
expect(flags['string-flag']).toBe('is bob');
expect(flags.cat).toBe(false);
});
it('presets flags from top-level bootstrap option', async () => {
const mockPlatform = createBasicPlatform();
const { ldc } = setupClient(mockPlatform, { disableNetwork: true, initialContext: context });
await ldc.start({ bootstrap: goodBootstrapData });
const flags = ldc.allFlags();
expect(flags.killswitch).toBe(true);
expect(flags['string-flag']).toBe('is bob');
});
it('makes flags available synchronously before identify completes', async () => {
const mockPlatform = createBasicPlatform();
const { ldc } = setupClient(mockPlatform, { disableNetwork: true, initialContext: context });
const startPromise = ldc.start({
identifyOptions: { bootstrap: goodBootstrapDataWithReasons },
});
const flags = ldc.allFlags();
expect(flags['string-flag']).toBe('is bob');
expect(flags.killswitch).toBe(true);
await startPromise;
});
it('supports bootstrap data with evaluation reasons', async () => {
const mockPlatform = createBasicPlatform();
const { ldc } = setupClient(mockPlatform, { disableNetwork: true, initialContext: context });
await ldc.start({
identifyOptions: { bootstrap: goodBootstrapDataWithReasons },
});
expect(ldc.jsonVariationDetail('json', undefined)).toEqual({
reason: { kind: 'OFF' },
value: ['a', 'b', 'c', 'd'],
variationIndex: 1,
});
});
it('prefers identifyOptions.bootstrap over top-level bootstrap', async () => {
const mockPlatform = createBasicPlatform();
const { ldc } = setupClient(mockPlatform, { disableNetwork: true, initialContext: context });
const differentBootstrap = {
'other-flag': true,
$flagsState: { 'other-flag': { variation: 0, version: 1 } },
$valid: true,
};
await ldc.start({
bootstrap: goodBootstrapData,
identifyOptions: { bootstrap: differentBootstrap },
});
const flags = ldc.allFlags();
expect(flags['other-flag']).toBe(true);
expect(flags.killswitch).toBeUndefined();
});
it('parses bootstrap data only once when using start()', async () => {
const readFlagsFromBootstrapSpy = jest.spyOn(bootstrapModule, 'readFlagsFromBootstrap');
const mockPlatform = createBasicPlatform();
const { ldc } = setupClient(mockPlatform, { disableNetwork: true, initialContext: context });
await ldc.start({
identifyOptions: { bootstrap: goodBootstrapDataWithReasons },
});
expect(readFlagsFromBootstrapSpy).toHaveBeenCalledTimes(1);
expect(readFlagsFromBootstrapSpy).toHaveBeenCalledWith(
expect.anything(),
goodBootstrapDataWithReasons,
);
readFlagsFromBootstrapSpy.mockRestore();
});
});
describe('requiresStart guard', () => {
it('blocks identify before start when requiresStart is true', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc, logger } = setupClient(mockPlatform, {
requiresStart: true,
initialContext: context,
});
const result = await ldc.identify({ kind: 'user', key: 'other-user' });
expect(result.status).toBe('error');
if (result.status === 'error') {
expect(result.error.message).toBe('Identify called before start');
}
expect(logger.error).toHaveBeenCalledWith(
'The client must be started before a context can be identified. Call start() prior to identifying a context.',
);
});
it('allows identify after start when requiresStart is true', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { requiresStart: true, initialContext: context });
await ldc.start();
const result = await ldc.identify({ kind: 'user', key: 'other-user' });
expect(result.status).toBe('completed');
});
it('allows identify without start when requiresStart is false', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { requiresStart: false });
const result = await ldc.identify(context);
expect(result.status).toBe('completed');
});
it('allows concurrent identifies after start', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { requiresStart: true, initialContext: context });
const startPromise = ldc.start();
const promise1 = ldc.identify({ kind: 'user', key: 'user-1' });
const promise2 = ldc.identify({ kind: 'user', key: 'user-2' });
const promise3 = ldc.identify({ kind: 'user', key: 'user-3' });
const [startResult, result1, result2, result3] = await Promise.all([
startPromise,
promise1,
promise2,
promise3,
]);
expect(startResult.status).toBe('complete');
expect(result1.status).toBe('completed');
expect(result2.status).toBe('completed');
expect(result3.status).toBe('completed');
});
});
describe('waitForInitialization integration', () => {
it('resolves waitForInitialization when start completes', async () => {
const mockPlatform = setupStreamingPlatform();
const { ldc } = setupClient(mockPlatform, { initialContext: context });
const waitPromise = ldc.waitForInitialization({ timeout: 10 });
const startPromise = ldc.start();
const [waitResult, startResult] = await Promise.all([waitPromise, startPromise]);
expect(waitResult.status).toBe('complete');
expect(startResult.status).toBe('complete');
});
});
});