|
1 | 1 | import { act, renderHook, waitFor } from '@testing-library/react'; |
2 | 2 |
|
| 3 | +import { createTrigger, renderHookServer } from '@/tests'; |
| 4 | + |
3 | 5 | import { useBattery } from './useBattery'; |
4 | 6 |
|
5 | | -const events: Record<string, () => void> = {}; |
| 7 | +const trigger = createTrigger<string, () => void>(); |
6 | 8 | const mockBatteryManager = { |
7 | 9 | charging: true, |
8 | 10 | chargingTime: 0, |
9 | 11 | dischargingTime: 5, |
10 | 12 | level: 1, |
11 | 13 | addEventListener: (type: string, callback: () => void) => { |
12 | | - events[type] = callback; |
| 14 | + trigger.add(type, callback); |
13 | 15 | }, |
14 | 16 | removeEventListener: (type: string, callback: () => void) => { |
15 | | - if (events[type] === callback) { |
16 | | - delete events[type]; |
| 17 | + if (trigger.get(type) === callback) { |
| 18 | + trigger.delete(type); |
17 | 19 | } |
18 | 20 | }, |
19 | 21 | dispatchEvent: (event: Event) => { |
20 | | - events[event.type]?.(); |
| 22 | + trigger.callback(event.type); |
21 | 23 | return true; |
22 | 24 | } |
23 | 25 | }; |
@@ -59,24 +61,37 @@ it('Should use battery', async () => { |
59 | 61 | ); |
60 | 62 | }); |
61 | 63 |
|
62 | | -it('Should correct return for unsupported', async () => { |
| 64 | +it('Should use battery on server side', async () => { |
| 65 | + const { result } = renderHookServer(useBattery); |
| 66 | + |
| 67 | + expect(result.current).toEqual({ |
| 68 | + supported: false, |
| 69 | + value: { |
| 70 | + charging: false, |
| 71 | + chargingTime: 0, |
| 72 | + dischargingTime: 0, |
| 73 | + level: 0, |
| 74 | + loading: true |
| 75 | + } |
| 76 | + }); |
| 77 | +}); |
| 78 | + |
| 79 | +it('Should use battery for unsupported', async () => { |
63 | 80 | Object.assign(navigator, { |
64 | 81 | getBattery: undefined |
65 | 82 | }); |
66 | 83 | const { result } = renderHook(useBattery); |
67 | 84 |
|
68 | | - await waitFor(() => |
69 | | - expect(result.current).toEqual({ |
70 | | - supported: false, |
71 | | - value: { |
72 | | - charging: false, |
73 | | - chargingTime: 0, |
74 | | - dischargingTime: 0, |
75 | | - level: 0, |
76 | | - loading: false |
77 | | - } |
78 | | - }) |
79 | | - ); |
| 85 | + expect(result.current).toEqual({ |
| 86 | + supported: false, |
| 87 | + value: { |
| 88 | + charging: false, |
| 89 | + chargingTime: 0, |
| 90 | + dischargingTime: 0, |
| 91 | + level: 0, |
| 92 | + loading: false |
| 93 | + } |
| 94 | + }); |
80 | 95 | }); |
81 | 96 |
|
82 | 97 | it('Should handle levelchange event', async () => { |
|
0 commit comments