Repository navigation
Expand file tree
/
Copy pathusePinHandler.test.tsx
More file actions
228 lines (211 loc) Β· 7.97 KB
/
Copy pathusePinHandler.test.tsx
File metadata and controls
228 lines (211 loc) Β· 7.97 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
import React from 'react';
import { act, renderHook, type RenderHookResult } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { nowNs } from 'stream-chat';
import type { Channel as ChannelType, LocalMessage, StreamChat } from 'stream-chat';
import { usePinHandler } from '../usePinHandler';
import {
generateChannel,
generateMessage,
generateUser,
getOrCreateChannelApi,
getTestClientWithUser,
useMockedApis,
} from '../../../../mock-builders';
import { Channel } from '../../../Channel';
import { Chat } from '../../../Chat';
// `usePinHandler` updates the message optimistically through `messagePaginator.ingestItem`,
// rolls back only the pin fields when the request fails, and rethrows so callers (the Pin
// message action) can show an error notification instead of a success one.
let channel: ChannelType;
let client: StreamChat;
const mouseEventMock = fromPartial<React.BaseSyntheticEvent>({
preventDefault: vi.fn(() => {}),
});
async function renderUsePinHandler(
message: LocalMessage,
notifications?: Parameters<typeof usePinHandler>[1],
) {
const wrapper = ({ children }: React.PropsWithChildren) => (
<Chat client={client}>
<Channel channel={channel}>{children}</Channel>
</Chat>
);
let rendered: RenderHookResult<ReturnType<typeof usePinHandler>, unknown>;
await act(async () => {
rendered = await renderHook(() => usePinHandler(message, notifications), {
wrapper,
});
});
return rendered!.result.current;
}
// Keeps the pin/unpin request pending; the returned function rejects it.
const mockPendingRequest = (method: 'pinMessage' | 'unpinMessage') => {
let rejectRequest: (error: Error) => void = () => {};
vi.spyOn(client, method).mockReturnValue(
new Promise((_, reject) => {
rejectRequest = reject;
}),
);
return rejectRequest;
};
// Starts `handlePin` without awaiting it, so assertions can run while the request is pending.
const startHandlePin = (handlePin: ReturnType<typeof usePinHandler>['handlePin']) => {
let pending: ReturnType<typeof handlePin> = undefined;
act(() => {
pending = handlePin(mouseEventMock);
});
return pending;
};
const getStoredMessage = (id: string) => channel.messagePaginator.getItem(id);
describe('usePinHandler custom hook', () => {
beforeAll(async () => {
client = await getTestClientWithUser(generateUser());
const channelData = generateChannel();
useMockedApis(client, [getOrCreateChannelApi(channelData)]);
channel = client.channel('messaging', channelData.channel.id);
});
afterEach(() => {
vi.restoreAllMocks();
});
it.each([
{ method: 'pinMessage', pinned: false },
{ method: 'unpinMessage', pinned: true },
] as const)(
'should update the message optimistically when $method succeeds',
async ({ method, pinned }) => {
const requestSpy = vi.spyOn(client, method).mockResolvedValue(fromPartial({}));
const message = generateMessage({ cid: channel.cid, pinned }) as LocalMessage;
const { handlePin } = await renderUsePinHandler(message);
await act(async () => {
await handlePin(mouseEventMock);
});
expect(requestSpy).toHaveBeenCalledWith(message);
expect(getStoredMessage(message.id)).toEqual(
expect.objectContaining({ pinned: !pinned }),
);
},
);
it.each([
{ method: 'pinMessage', pinned: false },
{ method: 'unpinMessage', pinned: true },
] as const)(
'should roll back and throw when $method fails',
async ({ method, pinned }) => {
const rejectRequest = mockPendingRequest(method);
const message = generateMessage({ cid: channel.cid, pinned }) as LocalMessage;
const { handlePin } = await renderUsePinHandler(message);
const pending = startHandlePin(handlePin);
expect(getStoredMessage(message.id)).toEqual(
expect.objectContaining({ pinned: !pinned }),
);
await act(async () => {
rejectRequest(new Error('request failed'));
await expect(pending).rejects.toThrow('request failed');
});
expect(getStoredMessage(message.id)).toEqual(expect.objectContaining({ pinned }));
},
);
it('should keep updates that arrived while the request was pending when rolling back', async () => {
const rejectRequest = mockPendingRequest('pinMessage');
const message = generateMessage({
cid: channel.cid,
pinned: false,
text: 'original',
}) as LocalMessage;
const { handlePin } = await renderUsePinHandler(message);
const pending = startHandlePin(handlePin);
act(() => {
channel.messagePaginator.ingestItem({
...getStoredMessage(message.id)!,
text: 'edited while pinning',
});
});
await act(async () => {
rejectRequest(new Error('pin failed'));
await expect(pending).rejects.toThrow('pin failed');
});
expect(getStoredMessage(message.id)).toEqual(
expect.objectContaining({ pinned: false, text: 'edited while pinning' }),
);
});
it('should keep a pin state that changed while the request was pending', async () => {
const rejectRequest = mockPendingRequest('unpinMessage');
const originalPinner = generateUser();
const newerPinner = generateUser();
const message = generateMessage({
cid: channel.cid,
pinned: true,
pinned_by: originalPinner,
}) as LocalMessage;
const { handlePin } = await renderUsePinHandler(message);
const pending = startHandlePin(handlePin);
act(() => {
channel.messagePaginator.ingestItem({
...getStoredMessage(message.id)!,
pinned: true,
pinned_by: newerPinner,
});
});
await act(async () => {
rejectRequest(new Error('unpin failed'));
await expect(pending).rejects.toThrow('unpin failed');
});
expect(getStoredMessage(message.id)?.pinned_by).toEqual(newerPinner);
});
it('should keep a newer pin with the same pinned value that arrived while pinning', async () => {
const rejectRequest = mockPendingRequest('pinMessage');
const newerPinner = generateUser();
const newerPinnedAt = nowNs();
const message = generateMessage({ cid: channel.cid, pinned: false }) as LocalMessage;
const { handlePin } = await renderUsePinHandler(message);
const pending = startHandlePin(handlePin);
act(() => {
channel.messagePaginator.ingestItem({
...getStoredMessage(message.id)!,
pinned: true,
pinned_at: newerPinnedAt,
pinned_by: newerPinner,
});
});
await act(async () => {
rejectRequest(new Error('pin failed'));
await expect(pending).rejects.toThrow('pin failed');
});
expect(getStoredMessage(message.id)).toEqual(
expect.objectContaining({
pinned: true,
pinned_at: newerPinnedAt,
pinned_by: newerPinner,
}),
);
});
it('should notify and throw when pinning fails with notifications configured', async () => {
vi.spyOn(client, 'pinMessage').mockRejectedValue(new Error('pin failed'));
const notify = vi.fn();
const message = generateMessage({ cid: channel.cid, pinned: false }) as LocalMessage;
const { handlePin } = await renderUsePinHandler(message, {
getErrorNotification: () => 'custom pin error',
notify,
});
await act(async () => {
await expect(handlePin(mouseEventMock)).rejects.toThrow('pin failed');
});
expect(notify).toHaveBeenCalledWith('custom pin error', 'error');
});
it('should roll back even when the notify callback throws', async () => {
vi.spyOn(client, 'pinMessage').mockRejectedValue(new Error('pin failed'));
const message = generateMessage({ cid: channel.cid, pinned: false }) as LocalMessage;
const { handlePin } = await renderUsePinHandler(message, {
notify: () => {
throw new Error('notify failed');
},
});
await act(async () => {
await expect(handlePin(mouseEventMock)).rejects.toThrow('notify failed');
});
expect(getStoredMessage(message.id)).toEqual(
expect.objectContaining({ pinned: false }),
);
});
});