-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
useCancelling.ts
80 lines (74 loc) · 2.26 KB
/
useCancelling.ts
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
import { ArticleResource } from '__tests__/new';
import { renderHook, act } from '@testing-library/react-hooks';
import nock from 'nock';
import useCancelling from '../useCancelling';
describe('useCancelling()', () => {
const payload = {
id: '6',
title: 'lala',
};
const payload2 = {
id: '7',
title: 'second one',
};
beforeAll(() => {
jest.useFakeTimers();
const mynock = nock(/.*/)
.persist()
.defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Access-Token',
'Content-Type': 'application/json',
})
.options(/.*/)
.reply(200);
mynock
.get(`/article/${payload.id}`)
.delay(2000)
.reply(200, payload)
.get(`/article/${payload2.id}`)
.delay(2000)
.reply(200, payload2);
});
afterAll(() => {
jest.useRealTimers();
nock.cleanAll();
});
it('should abort when props change and resolve when kept the same', async () => {
const { result, rerender } = renderHook(
({ id }: { id: string }) => {
return useCancelling(ArticleResource.detail(), { id });
},
{ initialProps: { id: '6' } },
);
const firstendpoint = result.current;
const ogPromise = result.current({ id: '6' });
jest.advanceTimersByTime(10);
act(() => rerender({ id: '7' }));
expect(result.current).not.toBe(firstendpoint);
expect(ogPromise).rejects.toMatchInlineSnapshot(`[AbortError: Aborted]`);
const nextPromise = result.current({ id: '7' });
jest.advanceTimersByTime(2000);
expect(nextPromise).resolves.toMatchInlineSnapshot(`
Object {
"id": "7",
"title": "second one",
}
`);
act(() => rerender({ id: '7' }));
});
it('should remain === if params does not change', () => {
const { result, rerender } = renderHook(
({ id }: { id: string }) => {
return useCancelling(ArticleResource.detail(), { id });
},
{ initialProps: { id: '6' } },
);
let lastendpoint = result.current;
act(() => rerender({ id: '6' }));
expect(result.current).toBe(lastendpoint);
lastendpoint = result.current;
act(() => rerender({ id: '6' }));
expect(result.current).toBe(lastendpoint);
});
});