-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathuseFlagStatus.test.tsx
120 lines (98 loc) · 2.69 KB
/
useFlagStatus.test.tsx
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
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import useFlagsStatus from './useFlagsStatus';
import FlagProvider from './FlagProvider';
import { UnleashClient } from 'unleash-proxy-client';
const TestComponent = () => {
const { flagsReady } = useFlagsStatus();
return <div>{flagsReady ? 'flagsReady' : 'loading'}</div>;
};
const ErrorTestComponent = () => {
const { flagsError } = useFlagsStatus();
return <div>{flagsError ? 'flagsError' : 'no issue'}</div>;
};
const mockClient = {
on: vi.fn(),
off: vi.fn(),
start: vi.fn(),
stop: vi.fn(),
updateContext: vi.fn(),
isEnabled: vi.fn(),
getVariant: vi.fn(),
isReady: vi.fn(),
} as unknown as UnleashClient;
test('should initialize', async () => {
const onEventHandler = (event: string, callback: () => void) => {
if (event === 'ready') {
callback();
}
};
mockClient.on = onEventHandler as typeof mockClient.on;
const ui = (
<FlagProvider unleashClient={mockClient}>
<TestComponent />
</FlagProvider>
);
render(ui);
await waitFor(() => {
expect(screen.queryByText('flagsReady')).toBeInTheDocument();
});
});
// https://github.com/Unleash/proxy-client-react/issues/168
test('should start when already initialized client is passed', async () => {
const client = new UnleashClient({
url: 'http://localhost:4242/api',
fetch: async () =>
new Promise((resolve) => {
setTimeout(() =>
resolve({
status: 200,
ok: true,
json: async () => ({
toggles: [],
}),
headers: new Headers(),
})
);
}),
clientKey: '123',
appName: 'test',
});
await client.start();
expect(client.isReady()).toBe(true);
const ui = (
<FlagProvider unleashClient={client}>
<TestComponent />
</FlagProvider>
);
render(ui);
await waitFor(() => {
expect(screen.queryByText('flagsReady')).toBeInTheDocument();
});
});
test('should handle client errors', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
const client = new UnleashClient({
url: 'http://localhost:4242/api',
fetch: async () => {
throw new Error('test error');
},
clientKey: '123',
appName: 'test',
});
await client.start();
const ui = (
<FlagProvider unleashClient={client}>
<ErrorTestComponent />
</FlagProvider>
);
render(ui);
await waitFor(() => {
expect(screen.queryByText('flagsError')).toBeInTheDocument();
});
expect(consoleError).toHaveBeenCalledWith(
'Unleash: unable to fetch feature toggles',
expect.any(Error)
);
consoleError.mockRestore();
});