forked from Talenttrust/Talenttrust-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWalletConnectButton.test.tsx
More file actions
387 lines (297 loc) · 12.4 KB
/
Copy pathWalletConnectButton.test.tsx
File metadata and controls
387 lines (297 loc) · 12.4 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
import React from 'react';
import { act, fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import { WalletConnectButton } from '../WalletConnectButton';
import { WalletContextType, useWallet } from '@/contexts/WalletContext';
import * as truncateAddressModule from '@/lib/truncateAddress';
import { testA11y } from '@/test-utils/a11y';
jest.mock('@/contexts/WalletContext', () => ({
useWallet: jest.fn(),
}));
const mockShowError = jest.fn();
jest.mock('@/components/toast/toast-provider', () => ({
useToast: jest.fn(() => ({ showError: mockShowError })),
}));
const mockUseWallet = useWallet as jest.MockedFunction<typeof useWallet>;
const COPY_ICON_PATH = 'M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z';
const COPIED_ICON_PATH = 'M5 13l4 4L19 7';
const originalClipboard = navigator.clipboard;
function createWalletState(overrides: Partial<WalletContextType> = {}): WalletContextType {
return {
address: null,
isConnecting: false,
error: null,
connect: jest.fn(),
disconnect: jest.fn(),
...overrides,
};
}
function installClipboardMock() {
const writeText = jest.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
return writeText;
}
function getButtonIconPath(button: HTMLElement) {
return button.querySelector('path')?.getAttribute('d');
}
describe('WalletConnectButton', () => {
beforeEach(() => {
jest.clearAllMocks();
jest.useFakeTimers();
});
afterEach(() => {
act(() => {
jest.runOnlyPendingTimers();
});
jest.useRealTimers();
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: originalClipboard,
});
});
it('renders the disconnected branch and calls connect when clicked', async () => {
const connect = jest.fn();
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
mockUseWallet.mockReturnValue(createWalletState({ connect }));
render(<WalletConnectButton />);
const connectButton = screen.getByRole('button', { name: 'Connect wallet' });
expect(connectButton).toBeEnabled();
expect(connectButton).toHaveTextContent('Connect Wallet');
expect(screen.queryByRole('button', { name: 'Copy address to clipboard' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Disconnect wallet' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Retry wallet connection' })).not.toBeInTheDocument();
await user.click(connectButton);
expect(connect).toHaveBeenCalledTimes(1);
});
it('renders the connecting branch with a disabled button and spinner', () => {
mockUseWallet.mockReturnValue(createWalletState({ isConnecting: true }));
render(<WalletConnectButton />);
const connectButton = screen.getByRole('button', { name: 'Connect wallet' });
expect(connectButton).toBeDisabled();
expect(connectButton).toHaveTextContent('Connecting...');
expect(connectButton.querySelector('svg.animate-spin')).toBeInTheDocument();
expect(screen.queryByText(/connection error/i)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Disconnect wallet' })).not.toBeInTheDocument();
});
it('renders the error branch and retries the connection', async () => {
const connect = jest.fn();
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
mockUseWallet.mockReturnValue(createWalletState({
error: 'Connection failed',
connect,
}));
render(<WalletConnectButton />);
expect(screen.getByText('Connection Error')).toBeInTheDocument();
const retryButton = screen.getByRole('button', { name: 'Retry wallet connection' });
expect(retryButton).toHaveTextContent('Retry');
expect(screen.queryByRole('button', { name: 'Connect wallet' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Disconnect wallet' })).not.toBeInTheDocument();
await user.click(retryButton);
expect(connect).toHaveBeenCalledTimes(1);
});
it('renders the connected branch using truncateAddress and exposes copy and disconnect controls', () => {
const address = '0x71C7656EC7ab88b098defB751B7401B5f6d8976F';
const truncateAddressSpy = jest.spyOn(truncateAddressModule, 'truncateAddress')
.mockReturnValue('0x71C7...976F');
mockUseWallet.mockReturnValue(createWalletState({ address }));
installClipboardMock();
render(<WalletConnectButton />);
expect(truncateAddressSpy).toHaveBeenCalledWith(address);
expect(screen.getByText('0x71C7...976F')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Copy address to clipboard' })).toHaveAttribute('title', 'Copy address');
expect(screen.getByRole('button', { name: 'Disconnect wallet' })).toHaveAttribute('title', 'Disconnect wallet');
expect(screen.queryByRole('button', { name: 'Connect wallet' })).not.toBeInTheDocument();
});
it('copies the full address, swaps to the success icon, and resets after 2 seconds', async () => {
const address = '0xABCDEF1234567890';
const writeText = installClipboardMock();
mockUseWallet.mockReturnValue(createWalletState({ address }));
render(<WalletConnectButton />);
const copyButton = screen.getByRole('button', { name: 'Copy address to clipboard' });
expect(getButtonIconPath(copyButton)).toBe(COPY_ICON_PATH);
await act(async () => {
fireEvent.click(copyButton);
});
await act(async () => {
await Promise.resolve();
});
expect(writeText).toHaveBeenCalledWith(address);
expect(mockShowError).not.toHaveBeenCalled();
expect(
getButtonIconPath(screen.getByRole('button', { name: 'Copy address to clipboard' })),
).toBe(COPIED_ICON_PATH);
act(() => {
jest.advanceTimersByTime(1999);
});
expect(
getButtonIconPath(screen.getByRole('button', { name: 'Copy address to clipboard' })),
).toBe(COPIED_ICON_PATH);
act(() => {
jest.advanceTimersByTime(1);
});
expect(
getButtonIconPath(screen.getByRole('button', { name: 'Copy address to clipboard' })),
).toBe(COPY_ICON_PATH);
});
it('calls disconnect from the connected branch', async () => {
const disconnect = jest.fn();
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
mockUseWallet.mockReturnValue(createWalletState({
address: '0x1234567890abcdef1234567890abcdef12345678',
disconnect,
}));
installClipboardMock();
render(<WalletConnectButton />);
await user.click(screen.getByRole('button', { name: 'Disconnect wallet' }));
expect(disconnect).toHaveBeenCalledTimes(1);
});
it('handles clipboard write failure gracefully', async () => {
const address = '0xABCDEF1234567890';
const writeText = jest.fn().mockRejectedValue(new Error('Write failed'));
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
mockUseWallet.mockReturnValue(createWalletState({ address }));
render(<WalletConnectButton />);
const copyButton = screen.getByRole('button', { name: 'Copy address to clipboard' });
expect(getButtonIconPath(copyButton)).toBe(COPY_ICON_PATH);
await act(async () => {
fireEvent.click(copyButton);
});
await act(async () => {
await Promise.resolve();
});
// Verify that the error toast was shown
expect(mockShowError).toHaveBeenCalledWith({
title: 'Copy failed',
description: 'Unable to copy the address to your clipboard. Please try again.',
});
// Icon should remain as copy (not change to checkmark)
expect(getButtonIconPath(copyButton)).toBe(COPY_ICON_PATH);
});
it('handles missing clipboard API gracefully', async () => {
const address = '0xABCDEF1234567890';
// Simulate missing clipboard API
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
mockUseWallet.mockReturnValue(createWalletState({ address }));
render(<WalletConnectButton />);
const copyButton = screen.getByRole('button', { name: 'Copy address to clipboard' });
await act(async () => {
fireEvent.click(copyButton);
});
await act(async () => {
await Promise.resolve();
});
// Verify that the appropriate error toast was shown
expect(mockShowError).toHaveBeenCalledWith({
title: 'Copy not supported',
description: 'Your browser does not support clipboard access. Please copy the address manually.',
});
// Icon should remain as copy (not change to checkmark)
expect(getButtonIconPath(copyButton)).toBe(COPY_ICON_PATH);
});
it('handles rapid consecutive copy clicks and only shows final success/error', async () => {
const address = '0xABCDEF1234567890';
const writeText = jest.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
mockUseWallet.mockReturnValue(createWalletState({ address }));
render(<WalletConnectButton />);
const copyButton = screen.getByRole('button', { name: 'Copy address to clipboard' });
// First click
await act(async () => {
fireEvent.click(copyButton);
});
await act(async () => {
await Promise.resolve();
});
expect(writeText).toHaveBeenCalledTimes(1);
expect(getButtonIconPath(copyButton)).toBe(COPIED_ICON_PATH);
// Second click before reset (should cancel first timer and set new one)
await act(async () => {
fireEvent.click(copyButton);
});
await act(async () => {
await Promise.resolve();
});
expect(writeText).toHaveBeenCalledTimes(2);
expect(getButtonIconPath(copyButton)).toBe(COPIED_ICON_PATH);
// Advance 1999ms (almost to first reset)
act(() => {
jest.advanceTimersByTime(1999);
});
expect(getButtonIconPath(copyButton)).toBe(COPIED_ICON_PATH);
// Advance 1ms more (now at 2000ms from second click, should reset)
act(() => {
jest.advanceTimersByTime(1);
});
expect(getButtonIconPath(copyButton)).toBe(COPY_ICON_PATH);
});
it('does not copy if address is not available', async () => {
const writeText = installClipboardMock();
mockUseWallet.mockReturnValue(createWalletState({ address: null }));
render(<WalletConnectButton />);
// Should render disconnected state, no copy button
expect(screen.queryByRole('button', { name: 'Copy address to clipboard' })).not.toBeInTheDocument();
expect(writeText).not.toHaveBeenCalled();
expect(mockShowError).not.toHaveBeenCalled();
});
it('cleans up timer on unmount to prevent state updates', async () => {
const address = '0xABCDEF1234567890';
installClipboardMock();
mockUseWallet.mockReturnValue(createWalletState({ address }));
const { unmount } = render(<WalletConnectButton />);
const copyButton = screen.getByRole('button', { name: 'Copy address to clipboard' });
await act(async () => {
fireEvent.click(copyButton);
});
await act(async () => {
await Promise.resolve();
});
expect(getButtonIconPath(copyButton)).toBe(COPIED_ICON_PATH);
// Unmount before timer fires
act(() => {
jest.advanceTimersByTime(500);
});
unmount();
// Advance past the reset timer
// (Should not cause errors even though component is unmounted)
expect(() => {
act(() => {
jest.advanceTimersByTime(1600);
});
}).not.toThrow();
});
it('has no accessibility violations in the connected state', async () => {
jest.useRealTimers();
mockUseWallet.mockReturnValue(createWalletState({
address: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F',
}));
installClipboardMock();
await testA11y(<WalletConnectButton />);
jest.useFakeTimers();
});
it('has no accessibility violations when clipboard write fails', async () => {
jest.useRealTimers();
const writeText = jest.fn().mockRejectedValue(new Error('Write failed'));
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
mockUseWallet.mockReturnValue(createWalletState({
address: '0x71C7656EC7ab88b098defB751B7401B5f6d8976F',
}));
await testA11y(<WalletConnectButton />);
jest.useFakeTimers();
});
});