-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathindex.test.ts
More file actions
420 lines (369 loc) · 13.6 KB
/
Copy pathindex.test.ts
File metadata and controls
420 lines (369 loc) · 13.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import { ExtendedMessenger } from '../../../ExtendedMessenger';
import { buildMessengerClientInitRequestMock } from '../../utils/test-utils';
import { MessengerClientInitRequest } from '../../types';
import {
PerpsController,
PerpsControllerMessenger,
PerpsControllerState,
InitializationState,
MARKET_SORTING_CONFIG,
PerpsPlatformDependencies,
} from '@metamask/perps-controller';
import { perpsControllerInit } from '.';
import { MOCK_ANY_NAMESPACE, MockAnyNamespace } from '@metamask/messenger';
import { getPerpsControllerMessenger } from '../../messengers/perps-controller-messenger';
import type { NotificationPreferences } from '@metamask/authenticated-user-storage';
// Mock mobile-specific modules that ./index.ts imports to avoid pulling in
// Engine and React Native dependencies in the test environment
jest.mock(
'../../../../components/UI/Perps/adapters/mobileInfrastructure',
() => ({
createMobileInfrastructure: jest.fn(() => ({})),
createMobileClientConfig: jest.fn(() => ({})),
}),
);
jest.mock('../../../../components/UI/Perps/utils/e2eBridgePerps', () => ({
applyE2EControllerMocks: jest.fn(),
}));
jest.mock('@metamask/perps-controller', () => {
const actualPerpsController = jest.requireActual(
'@metamask/perps-controller/PerpsController',
);
const actualUtils = jest.requireActual('@metamask/perps-controller/utils');
const actualConstants = jest.requireActual(
'@metamask/perps-controller/constants',
);
return {
controllerName: actualPerpsController.controllerName,
getDefaultPerpsControllerState:
actualPerpsController.getDefaultPerpsControllerState,
InitializationState: actualPerpsController.InitializationState,
PerpsController: jest.fn(),
parseCommaSeparatedString: actualUtils.parseCommaSeparatedString,
MARKET_SORTING_CONFIG: actualConstants.MARKET_SORTING_CONFIG,
};
});
describe('perps controller init', () => {
const perpsControllerClassMock = jest.mocked(PerpsController);
let initRequestMock: jest.Mocked<
MessengerClientInitRequest<PerpsControllerMessenger>
>;
beforeEach(() => {
jest.resetAllMocks();
const baseControllerMessenger = new ExtendedMessenger<MockAnyNamespace>({
namespace: MOCK_ANY_NAMESPACE,
});
// Create messenger client init request mock
initRequestMock = buildMessengerClientInitRequestMock(
baseControllerMessenger,
);
// Mock getState to return proper Redux state structure for feature flags
// Using Partial since we only need RemoteFeatureFlagController for this test
initRequestMock.getState.mockReturnValue({
engine: {
backgroundState: {
RemoteFeatureFlagController: {
remoteFeatureFlags: {},
cacheTimestamp: 0,
},
} as Partial<
ReturnType<
typeof initRequestMock.getState
>['engine']['backgroundState']
>,
},
} as ReturnType<typeof initRequestMock.getState>);
});
it('returns controller instance', () => {
expect(perpsControllerInit(initRequestMock).controller).toBeInstanceOf(
PerpsController,
);
});
it('controller state should be default state when no initial state is passed in', () => {
const defaultPerpsControllerState = jest
.requireActual('@metamask/perps-controller/PerpsController')
.getDefaultPerpsControllerState();
perpsControllerInit(initRequestMock);
const perpsControllerState =
perpsControllerClassMock.mock.calls[0][0].state;
expect(perpsControllerState).toEqual(defaultPerpsControllerState);
});
it('controller state should be initial state when initial state is passed in', () => {
const initialPerpsControllerState: PerpsControllerState = {
activeProvider: 'hyperliquid',
isTestnet: true,
accountState: null,
perpsBalances: {},
depositInProgress: false,
lastDepositTransactionId: null,
lastDepositResult: null,
lastError: null,
lastUpdateTimestamp: Date.now(),
isEligible: false,
isFirstTimeUser: {
testnet: true,
mainnet: true,
},
hasPlacedFirstOrder: {
testnet: false,
mainnet: false,
},
watchlistMarkets: {
testnet: [],
mainnet: [],
},
tradeConfigurations: {
testnet: {},
mainnet: {},
},
marketFilterPreferences: {
optionId: MARKET_SORTING_CONFIG.DefaultSortOptionId,
direction: MARKET_SORTING_CONFIG.DefaultDirection,
},
hip3ConfigVersion: 0,
withdrawInProgress: false,
lastWithdrawResult: null,
lastCompletedWithdrawalTimestamp: null,
lastCompletedWithdrawalTxHashes: [],
withdrawalRequests: [],
withdrawalProgress: {
progress: 0,
lastUpdated: Date.now(),
activeWithdrawalId: null,
},
depositRequests: [],
initializationState: InitializationState.Uninitialized,
initializationError: null,
initializationAttempts: 0,
selectedPaymentToken: null,
cachedMarketDataByProvider: {},
cachedUserDataByProvider: {},
};
initRequestMock.persistedState = {
...initRequestMock.persistedState,
PerpsController: initialPerpsControllerState,
};
perpsControllerInit(initRequestMock);
const perpsControllerState =
perpsControllerClassMock.mock.calls[0][0].state;
expect(perpsControllerState).toStrictEqual(initialPerpsControllerState);
});
});
// ---------------------------------------------------------------------------
// Integration: watchlist ↔ AuthenticatedUserStorageService
//
// The describe block above mocks PerpsController as jest.fn() (needed to test
// the init wiring). These tests need the real controller, so they use
// jest.requireActual to reach the preview build directly.
// ---------------------------------------------------------------------------
function buildSeedPrefs(
overrides: Partial<NotificationPreferences> = {},
): NotificationPreferences {
return {
walletActivity: {
inAppNotificationsEnabled: false,
pushNotificationsEnabled: false,
accounts: [],
},
marketing: {
inAppNotificationsEnabled: false,
pushNotificationsEnabled: false,
},
perps: {
inAppNotificationsEnabled: false,
pushNotificationsEnabled: false,
watchlistMarkets: {
hyperliquid: { testnet: [], mainnet: [] },
myx: { testnet: [], mainnet: [] },
},
},
socialAI: {
inAppNotificationsEnabled: false,
pushNotificationsEnabled: false,
mutedTraderProfileIds: [],
},
...overrides,
};
}
function buildTestInfrastructure(): PerpsPlatformDependencies {
return {
logger: { error: jest.fn() },
debugLogger: { log: jest.fn() },
metrics: { isEnabled: jest.fn(() => false), trackPerpsEvent: jest.fn() },
performance: { now: jest.fn(() => 0) },
streamManager: {
pauseChannel: jest.fn(),
resumeChannel: jest.fn(),
clearAllChannels: jest.fn(),
},
featureFlags: { validateVersionGated: jest.fn(() => false) },
marketDataFormatters: {
formatVolume: jest.fn(() => ''),
formatPerpsFiat: jest.fn(() => ''),
formatPercentage: jest.fn(() => ''),
priceRangesUniversal: [],
},
cacheInvalidator: { invalidate: jest.fn(), invalidateAll: jest.fn() },
diskCache: {
// Called synchronously in the constructor (#hydrateCacheFromDiskSync).
getItemSync: jest.fn(() => null),
getItem: jest.fn(() => Promise.resolve(null)),
setItem: jest.fn(() => Promise.resolve()),
removeItem: jest.fn(() => Promise.resolve()),
},
tracer: {
trace: jest.fn(),
endTrace: jest.fn(),
setMeasurement: jest.fn(),
addBreadcrumb: jest.fn(),
},
rewards: { getPerpsDiscountForAccount: jest.fn(() => Promise.resolve(0)) },
};
}
interface GetNotificationPreferencesAction {
type: 'AuthenticatedUserStorageService:getNotificationPreferences';
handler: () => Promise<NotificationPreferences | null>;
}
interface PutNotificationPreferencesAction {
type: 'AuthenticatedUserStorageService:putNotificationPreferences';
handler: (prefs: NotificationPreferences) => Promise<void>;
}
function buildRealController(
getNotificationPreferencesImpl: () => Promise<NotificationPreferences | null>,
) {
// Use the real PerpsController from the preview build — the top-level
// jest.mock replaces it with jest.fn() for the init tests above, so we
// reach through with requireActual here.
const {
PerpsController: RealPerpsController,
getDefaultPerpsControllerState,
} = jest.requireActual('@metamask/perps-controller/PerpsController') as {
PerpsController: typeof PerpsController;
getDefaultPerpsControllerState: () => PerpsControllerState;
};
const baseMessenger = new ExtendedMessenger<
MockAnyNamespace,
GetNotificationPreferencesAction | PutNotificationPreferencesAction
>({
namespace: MOCK_ANY_NAMESPACE,
});
const getSpy = jest.fn().mockImplementation(getNotificationPreferencesImpl);
const putSpy = jest.fn().mockResolvedValue(undefined);
baseMessenger.registerActionHandler(
'AuthenticatedUserStorageService:getNotificationPreferences',
getSpy,
);
baseMessenger.registerActionHandler(
'AuthenticatedUserStorageService:putNotificationPreferences',
putSpy,
);
const controllerMessenger = getPerpsControllerMessenger(baseMessenger);
const controller = new RealPerpsController({
messenger: controllerMessenger,
state: getDefaultPerpsControllerState(),
infrastructure: buildTestInfrastructure(),
clientConfig: {},
});
return { controller, getSpy, putSpy };
}
describe('PerpsController watchlist ↔ AuthenticatedUserStorageService', () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe('toggleWatchlistMarket — add', () => {
it('calls putNotificationPreferences with the new symbol in hyperliquid.mainnet', async () => {
const { controller, putSpy } = buildRealController(() =>
Promise.resolve(buildSeedPrefs()),
);
await controller.toggleWatchlistMarket('BTC');
expect(putSpy).toHaveBeenCalledTimes(1);
expect(putSpy).toHaveBeenCalledWith(
expect.objectContaining({
perps: expect.objectContaining({
watchlistMarkets: expect.objectContaining({
hyperliquid: expect.objectContaining({
mainnet: expect.arrayContaining(['BTC']),
}),
}),
}),
}),
);
});
it('keeps the local watchlist state after a successful AUS write', async () => {
const { controller } = buildRealController(() =>
Promise.resolve(buildSeedPrefs()),
);
await controller.toggleWatchlistMarket('ETH');
expect(controller.getWatchlistMarkets()).toContain('ETH');
});
it('merges with existing remote symbols — does not overwrite the whole list', async () => {
const seedWithSol = buildSeedPrefs({
perps: {
inAppNotificationsEnabled: false,
pushNotificationsEnabled: false,
watchlistMarkets: {
hyperliquid: { testnet: [], mainnet: ['SOL'] },
myx: { testnet: [], mainnet: [] },
},
},
});
const { controller, putSpy } = buildRealController(() =>
Promise.resolve(seedWithSol),
);
// Seed local state with SOL first
await controller.toggleWatchlistMarket('SOL');
putSpy.mockClear();
await controller.toggleWatchlistMarket('BTC');
expect(putSpy).toHaveBeenCalledWith(
expect.objectContaining({
perps: expect.objectContaining({
watchlistMarkets: expect.objectContaining({
hyperliquid: expect.objectContaining({
mainnet: expect.arrayContaining(['SOL', 'BTC']),
}),
}),
}),
}),
);
});
});
describe('toggleWatchlistMarket — remove', () => {
it('calls putNotificationPreferences without the removed symbol', async () => {
const { controller, putSpy } = buildRealController(() =>
Promise.resolve(buildSeedPrefs()),
);
await controller.toggleWatchlistMarket('BTC'); // add
putSpy.mockClear();
await controller.toggleWatchlistMarket('BTC'); // remove
expect(putSpy).toHaveBeenCalledTimes(1);
const [calledPrefs] = putSpy.mock.calls[0] as [NotificationPreferences];
expect(
calledPrefs.perps.watchlistMarkets?.hyperliquid.mainnet,
).not.toContain('BTC');
});
it('reverts local state when the AUS write fails', async () => {
const { controller, putSpy } = buildRealController(() =>
Promise.resolve(buildSeedPrefs()),
);
await controller.toggleWatchlistMarket('BTC');
expect(controller.getWatchlistMarkets()).toContain('BTC');
putSpy.mockRejectedValueOnce(new Error('network error'));
await controller.toggleWatchlistMarket('BTC'); // remove attempt fails
expect(controller.getWatchlistMarkets()).toContain('BTC');
});
});
describe('AUS write is skipped when preferences blob is not yet initialised', () => {
it('does not call putNotificationPreferences when getNotificationPreferences returns null', async () => {
const { controller, putSpy } = buildRealController(() =>
Promise.resolve(null),
);
await controller.toggleWatchlistMarket('BTC');
expect(putSpy).not.toHaveBeenCalled();
});
it('keeps the optimistic local update even when the remote write is skipped', async () => {
const { controller } = buildRealController(() => Promise.resolve(null));
await controller.toggleWatchlistMarket('BTC');
expect(controller.getWatchlistMarkets()).toContain('BTC');
});
});
});