@explorins/pers-sdk-react-native 2.2.0-beta.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,420 @@
1
+ import React from 'react';
2
+ import { render, act, waitFor } from '@testing-library/react';
3
+ import '@testing-library/jest-dom';
4
+ import { PersSDKProvider, usePersSDK, PersSDKContext } from '../providers/PersSDKProvider';
5
+
6
+ // Store SDK instances for event emission
7
+ let mockSdkInstance: any = null;
8
+
9
+ // Mock the SDK core module BEFORE any imports use it
10
+ jest.mock('@explorins/pers-sdk/core', () => {
11
+ const createMockEventEmitter = () => {
12
+ const subscribers: Array<{ callback: (event: any) => void; options?: any }> = [];
13
+
14
+ return {
15
+ subscribe: jest.fn((callback: (event: any) => void, options?: any) => {
16
+ subscribers.push({ callback, options });
17
+ return () => {
18
+ const index = subscribers.findIndex(s => s.callback === callback);
19
+ if (index > -1) subscribers.splice(index, 1);
20
+ };
21
+ }),
22
+ emit: (event: any) => {
23
+ subscribers.forEach(({ callback, options }) => {
24
+ if (!options?.domains || options.domains.includes(event.domain)) {
25
+ callback(event);
26
+ }
27
+ });
28
+ },
29
+ _subscribers: subscribers
30
+ };
31
+ };
32
+
33
+ const MockPersSDK = jest.fn().mockImplementation(() => {
34
+ const events = createMockEventEmitter();
35
+ mockSdkInstance = {
36
+ events,
37
+ auth: {
38
+ ensureValidToken: jest.fn().mockResolvedValue(true)
39
+ },
40
+ users: {
41
+ getCurrentUser: jest.fn().mockResolvedValue({ id: 'refreshed-user', email: 'refreshed@test.com' })
42
+ },
43
+ restoreSession: jest.fn().mockResolvedValue(null)
44
+ };
45
+ return mockSdkInstance;
46
+ });
47
+
48
+ return {
49
+ PersSDK: MockPersSDK,
50
+ DefaultAuthProvider: jest.fn().mockImplementation(() => ({
51
+ getToken: jest.fn().mockResolvedValue('mock-token')
52
+ }))
53
+ };
54
+ });
55
+
56
+ // Mock platform-specific providers
57
+ jest.mock('../providers/react-native-http-client', () => ({
58
+ ReactNativeHttpClient: jest.fn().mockImplementation(() => ({}))
59
+ }));
60
+
61
+ jest.mock('../providers/react-native-auth-provider', () => ({
62
+ createReactNativeAuthProvider: jest.fn().mockReturnValue({
63
+ getToken: jest.fn().mockResolvedValue('mock-token')
64
+ })
65
+ }));
66
+
67
+ jest.mock('../providers/rn-dpop-provider', () => ({
68
+ ReactNativeDPoPProvider: jest.fn().mockImplementation(() => ({}))
69
+ }));
70
+
71
+ // Helper component to access context
72
+ const TestConsumer: React.FC<{ onContext: (ctx: PersSDKContext) => void }> = ({ onContext }) => {
73
+ const context = usePersSDK();
74
+ React.useEffect(() => {
75
+ onContext(context);
76
+ }, [context, onContext]);
77
+ return <div data-testid="consumer">Consumer</div>;
78
+ };
79
+
80
+ // Helper to emit events on the mock SDK
81
+ const emitAuthEvent = (type: string, details: any = {}) => {
82
+ if (mockSdkInstance?.events) {
83
+ mockSdkInstance.events.emit({
84
+ type,
85
+ domain: 'authentication',
86
+ details
87
+ });
88
+ }
89
+ };
90
+
91
+ describe('PersSDKProvider', () => {
92
+ beforeEach(() => {
93
+ jest.clearAllMocks();
94
+ mockSdkInstance = null;
95
+ });
96
+
97
+ describe('initialization', () => {
98
+ it('should initialize with null SDK when no config provided', async () => {
99
+ let capturedContext: PersSDKContext | null = null;
100
+
101
+ render(
102
+ <PersSDKProvider>
103
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
104
+ </PersSDKProvider>
105
+ );
106
+
107
+ await waitFor(() => {
108
+ expect(capturedContext).not.toBeNull();
109
+ });
110
+
111
+ expect(capturedContext!.sdk).toBeNull();
112
+ expect(capturedContext!.isInitialized).toBe(false);
113
+ expect(capturedContext!.isAuthenticated).toBe(false);
114
+ expect(capturedContext!.user).toBeNull();
115
+ });
116
+
117
+ it('should auto-initialize when config is provided', async () => {
118
+ let capturedContext: PersSDKContext | null = null;
119
+
120
+ render(
121
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
122
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
123
+ </PersSDKProvider>
124
+ );
125
+
126
+ await waitFor(() => {
127
+ expect(capturedContext?.isInitialized).toBe(true);
128
+ });
129
+
130
+ expect(capturedContext!.sdk).not.toBeNull();
131
+ });
132
+
133
+ it('should prevent multiple initializations', async () => {
134
+ const { PersSDK } = require('@explorins/pers-sdk/core');
135
+
136
+ let capturedContext: PersSDKContext | null = null;
137
+
138
+ render(
139
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
140
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
141
+ </PersSDKProvider>
142
+ );
143
+
144
+ await waitFor(() => {
145
+ expect(capturedContext?.isInitialized).toBe(true);
146
+ });
147
+
148
+ // Try to initialize again - should be ignored
149
+ await act(async () => {
150
+ await capturedContext!.initialize({ apiProjectKey: 'different-project' });
151
+ });
152
+
153
+ // Should only have been called once
154
+ expect(PersSDK).toHaveBeenCalledTimes(1);
155
+ });
156
+ });
157
+
158
+ describe('event handling', () => {
159
+ it('should set user on session_restored event', async () => {
160
+ let capturedContext: PersSDKContext | null = null;
161
+ const mockUser = { id: 'user-123', email: 'test@example.com' };
162
+
163
+ render(
164
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
165
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
166
+ </PersSDKProvider>
167
+ );
168
+
169
+ await waitFor(() => {
170
+ expect(capturedContext?.sdk).not.toBeNull();
171
+ });
172
+
173
+ // Emit session_restored event
174
+ await act(async () => {
175
+ emitAuthEvent('session_restored', { user: mockUser });
176
+ });
177
+
178
+ await waitFor(() => {
179
+ expect(capturedContext?.isAuthenticated).toBe(true);
180
+ expect(capturedContext?.user).toEqual(mockUser);
181
+ });
182
+ });
183
+
184
+ it('should set user on login_success event', async () => {
185
+ let capturedContext: PersSDKContext | null = null;
186
+ const mockUser = { id: 'user-456', email: 'login@example.com' };
187
+
188
+ render(
189
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
190
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
191
+ </PersSDKProvider>
192
+ );
193
+
194
+ await waitFor(() => {
195
+ expect(capturedContext?.sdk).not.toBeNull();
196
+ });
197
+
198
+ await act(async () => {
199
+ emitAuthEvent('login_success', { user: mockUser });
200
+ });
201
+
202
+ await waitFor(() => {
203
+ expect(capturedContext?.isAuthenticated).toBe(true);
204
+ expect(capturedContext?.user).toEqual(mockUser);
205
+ });
206
+ });
207
+
208
+ it('should clear user on logout_success event', async () => {
209
+ let capturedContext: PersSDKContext | null = null;
210
+ const mockUser = { id: 'user-789', email: 'logout@example.com' };
211
+
212
+ render(
213
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
214
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
215
+ </PersSDKProvider>
216
+ );
217
+
218
+ await waitFor(() => {
219
+ expect(capturedContext?.sdk).not.toBeNull();
220
+ });
221
+
222
+ // First, log in
223
+ await act(async () => {
224
+ emitAuthEvent('login_success', { user: mockUser });
225
+ });
226
+
227
+ await waitFor(() => {
228
+ expect(capturedContext?.isAuthenticated).toBe(true);
229
+ });
230
+
231
+ // Then logout
232
+ await act(async () => {
233
+ emitAuthEvent('logout_success', {});
234
+ });
235
+
236
+ await waitFor(() => {
237
+ expect(capturedContext?.isAuthenticated).toBe(false);
238
+ expect(capturedContext?.user).toBeNull();
239
+ });
240
+ });
241
+
242
+ it('should clear user on session_restoration_failed event', async () => {
243
+ let capturedContext: PersSDKContext | null = null;
244
+
245
+ render(
246
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
247
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
248
+ </PersSDKProvider>
249
+ );
250
+
251
+ await waitFor(() => {
252
+ expect(capturedContext?.sdk).not.toBeNull();
253
+ });
254
+
255
+ // Set initial authenticated state
256
+ await act(async () => {
257
+ capturedContext!.setAuthenticationState({ id: 'temp-user' } as any, true);
258
+ });
259
+
260
+ await waitFor(() => {
261
+ expect(capturedContext?.isAuthenticated).toBe(true);
262
+ });
263
+
264
+ // Emit session_restoration_failed
265
+ await act(async () => {
266
+ emitAuthEvent('session_restoration_failed', { error: 'Token expired' });
267
+ });
268
+
269
+ await waitFor(() => {
270
+ expect(capturedContext?.isAuthenticated).toBe(false);
271
+ expect(capturedContext?.user).toBeNull();
272
+ });
273
+ });
274
+
275
+ it('should NOT respond to AUTH_FAILED code (dead code was removed)', async () => {
276
+ // This test verifies that we no longer check for event.code === 'AUTH_FAILED'
277
+ // which was dead code that never triggered
278
+ let capturedContext: PersSDKContext | null = null;
279
+ const mockUser = { id: 'user-stay', email: 'stay@example.com' };
280
+
281
+ render(
282
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
283
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
284
+ </PersSDKProvider>
285
+ );
286
+
287
+ await waitFor(() => {
288
+ expect(capturedContext?.sdk).not.toBeNull();
289
+ });
290
+
291
+ // Log in first
292
+ await act(async () => {
293
+ emitAuthEvent('login_success', { user: mockUser });
294
+ });
295
+
296
+ await waitFor(() => {
297
+ expect(capturedContext?.isAuthenticated).toBe(true);
298
+ });
299
+
300
+ // Emit an event with code: 'AUTH_FAILED' - this should NOT clear user
301
+ // because we removed the dead code that checked for this
302
+ await act(async () => {
303
+ if (mockSdkInstance?.events) {
304
+ mockSdkInstance.events.emit({
305
+ type: 'some_other_event',
306
+ code: 'AUTH_FAILED', // This was the dead code path we removed
307
+ domain: 'authentication',
308
+ details: {}
309
+ });
310
+ }
311
+ });
312
+
313
+ // User should STILL be authenticated - the code: 'AUTH_FAILED' check is gone
314
+ expect(capturedContext!.isAuthenticated).toBe(true);
315
+ expect(capturedContext!.user).toEqual(mockUser);
316
+ });
317
+ });
318
+
319
+ describe('usePersSDK hook', () => {
320
+ it('should throw error when used outside provider', () => {
321
+ // Suppress the expected error
322
+ const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
323
+
324
+ const TestComponent = () => {
325
+ usePersSDK();
326
+ return null;
327
+ };
328
+
329
+ expect(() => render(<TestComponent />)).toThrow(
330
+ 'usePersSDK must be used within a PersSDKProvider'
331
+ );
332
+
333
+ spy.mockRestore();
334
+ });
335
+ });
336
+
337
+ describe('context methods', () => {
338
+ it('should allow manual authentication state updates', async () => {
339
+ let capturedContext: PersSDKContext | null = null;
340
+ const mockUser = { id: 'manual-user', email: 'manual@example.com' };
341
+
342
+ render(
343
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
344
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
345
+ </PersSDKProvider>
346
+ );
347
+
348
+ await waitFor(() => {
349
+ expect(capturedContext?.isInitialized).toBe(true);
350
+ });
351
+
352
+ await act(async () => {
353
+ capturedContext!.setAuthenticationState(mockUser as any, true);
354
+ });
355
+
356
+ await waitFor(() => {
357
+ expect(capturedContext?.isAuthenticated).toBe(true);
358
+ expect(capturedContext?.user).toEqual(mockUser);
359
+ });
360
+ });
361
+
362
+ it('should refresh user data from SDK', async () => {
363
+ let capturedContext: PersSDKContext | null = null;
364
+
365
+ render(
366
+ <PersSDKProvider config={{ apiProjectKey: 'test-project' }}>
367
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
368
+ </PersSDKProvider>
369
+ );
370
+
371
+ await waitFor(() => {
372
+ expect(capturedContext?.isInitialized).toBe(true);
373
+ });
374
+
375
+ await act(async () => {
376
+ await capturedContext!.refreshUserData();
377
+ });
378
+
379
+ await waitFor(() => {
380
+ expect(capturedContext?.user).toEqual({ id: 'refreshed-user', email: 'refreshed@test.com' });
381
+ });
382
+ });
383
+
384
+ it('should throw error when refreshUserData called before init', async () => {
385
+ let capturedContext: PersSDKContext | null = null;
386
+
387
+ render(
388
+ <PersSDKProvider>
389
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
390
+ </PersSDKProvider>
391
+ );
392
+
393
+ await waitFor(() => {
394
+ expect(capturedContext).not.toBeNull();
395
+ });
396
+
397
+ await expect(capturedContext!.refreshUserData()).rejects.toThrow(
398
+ 'SDK not initialized'
399
+ );
400
+ });
401
+
402
+ it('should throw error when restoreSession called before init', async () => {
403
+ let capturedContext: PersSDKContext | null = null;
404
+
405
+ render(
406
+ <PersSDKProvider>
407
+ <TestConsumer onContext={(ctx) => { capturedContext = ctx; }} />
408
+ </PersSDKProvider>
409
+ );
410
+
411
+ await waitFor(() => {
412
+ expect(capturedContext).not.toBeNull();
413
+ });
414
+
415
+ await expect(capturedContext!.restoreSession()).rejects.toThrow(
416
+ 'SDK not initialized'
417
+ );
418
+ });
419
+ });
420
+ });
@@ -0,0 +1,83 @@
1
+ // Mock @explorins/pers-sdk/core
2
+
3
+ export interface PersConfig {
4
+ apiProjectKey?: string;
5
+ environment?: 'staging' | 'production';
6
+ captureWalletEvents?: boolean;
7
+ authProvider?: any;
8
+ dpop?: {
9
+ enabled?: boolean;
10
+ cryptoProvider?: any;
11
+ };
12
+ }
13
+
14
+ // Create mock event emitter factory
15
+ export const createMockEventEmitter = () => {
16
+ const subscribers: Array<{ callback: (event: any) => void; options?: any }> = [];
17
+
18
+ return {
19
+ subscribe: jest.fn((callback: (event: any) => void, options?: any) => {
20
+ subscribers.push({ callback, options });
21
+
22
+ // Replay immediately if requested
23
+ if (options?.replay) {
24
+ // No events to replay in mock
25
+ }
26
+
27
+ return () => {
28
+ const index = subscribers.findIndex(s => s.callback === callback);
29
+ if (index > -1) subscribers.splice(index, 1);
30
+ };
31
+ }),
32
+ emit: (event: any) => {
33
+ subscribers.forEach(({ callback, options }) => {
34
+ if (!options?.domains || options.domains.includes(event.domain)) {
35
+ callback(event);
36
+ }
37
+ });
38
+ },
39
+ _subscribers: subscribers
40
+ };
41
+ };
42
+
43
+ // Mock PersSDK class
44
+ export class PersSDK {
45
+ events: ReturnType<typeof createMockEventEmitter>;
46
+ auth: any;
47
+ users: any;
48
+
49
+ constructor(_httpClient: any, _config: PersConfig) {
50
+ this.events = createMockEventEmitter();
51
+ this.auth = {
52
+ ensureValidToken: jest.fn().mockResolvedValue(true)
53
+ };
54
+ this.users = {
55
+ getCurrentUser: jest.fn().mockResolvedValue({ id: 'user-1', email: 'test@test.com' })
56
+ };
57
+ }
58
+
59
+ restoreSession = jest.fn().mockResolvedValue(null);
60
+
61
+ // Helper for tests to emit events
62
+ _mockEmitEvent(event: any) {
63
+ this.events.emit(event);
64
+ }
65
+ }
66
+
67
+ // Mock DefaultAuthProvider
68
+ export class DefaultAuthProvider {
69
+ constructor(_projectKey?: string, _options?: any) {}
70
+ }
71
+
72
+ // Mock manager types
73
+ export type AuthManager = any;
74
+ export type UserManager = any;
75
+ export type TokenManager = any;
76
+ export type BusinessManager = any;
77
+ export type CampaignManager = any;
78
+ export type RedemptionManager = any;
79
+ export type TransactionManager = any;
80
+ export type PurchaseManager = any;
81
+ export type TenantManager = any;
82
+ export type AnalyticsManager = any;
83
+ export type DonationManager = any;
@@ -0,0 +1,17 @@
1
+ // Mock @explorins/pers-shared
2
+
3
+ export interface UserDTO {
4
+ id: string;
5
+ email?: string;
6
+ firstName?: string;
7
+ lastName?: string;
8
+ walletAddress?: string;
9
+ createdAt?: string;
10
+ updatedAt?: string;
11
+ }
12
+
13
+ export interface AdminDTO {
14
+ id: string;
15
+ email?: string;
16
+ role?: string;
17
+ }
@@ -0,0 +1,40 @@
1
+ import '@testing-library/jest-dom';
2
+
3
+ // Mock React Native modules
4
+ jest.mock('react-native', () => ({
5
+ Platform: {
6
+ OS: 'ios',
7
+ select: jest.fn((obj) => obj.ios || obj.default)
8
+ },
9
+ AppState: {
10
+ addEventListener: jest.fn(() => ({
11
+ remove: jest.fn()
12
+ })),
13
+ currentState: 'active'
14
+ }
15
+ }));
16
+
17
+ // Mock AsyncStorage
18
+ jest.mock('@react-native-async-storage/async-storage', () => ({
19
+ default: {
20
+ getItem: jest.fn(),
21
+ setItem: jest.fn(),
22
+ removeItem: jest.fn(),
23
+ clear: jest.fn(),
24
+ getAllKeys: jest.fn(() => Promise.resolve([]))
25
+ }
26
+ }));
27
+
28
+ // Silence console errors in tests unless explicitly needed
29
+ const originalConsoleError = console.error;
30
+ const originalConsoleWarn = console.warn;
31
+
32
+ beforeAll(() => {
33
+ console.error = jest.fn();
34
+ console.warn = jest.fn();
35
+ });
36
+
37
+ afterAll(() => {
38
+ console.error = originalConsoleError;
39
+ console.warn = originalConsoleWarn;
40
+ });
@@ -14,7 +14,7 @@ import type {
14
14
  DynamicContext,
15
15
  SortOrder
16
16
  } from '@explorins/pers-sdk';
17
- import type { RedemptionRedeemFilters, RedemptionFilterOptions } from '@explorins/pers-sdk/redemption';
17
+ import type { RedemptionRedeemFilters } from '@explorins/pers-sdk/redemption';
18
18
  import type { PaginationOptions } from '@explorins/pers-sdk';
19
19
 
20
20
  // Re-export for consumers
@@ -168,7 +168,7 @@ export const PersSDKProvider: React.FC<{
168
168
  }
169
169
  }
170
170
 
171
- if (event.type === 'logout_success' || event.type === 'session_restoration_failed' || event.code === 'AUTH_FAILED') {
171
+ if (event.type === 'logout_success' || event.type === 'session_restoration_failed') {
172
172
  setUser(null);
173
173
  setIsAuthenticated(false);
174
174
  }