-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathuseAsyncRequest.spec.tsx
48 lines (34 loc) · 1.27 KB
/
useAsyncRequest.spec.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
import { act, renderHook } from '@testing-library/react';
import { useAsyncRequest } from '../useAsyncRequest';
describe('useAsyncRequest', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('handle request with no response correctly', async () => {
const mockPromise = Promise.resolve();
const mockRequest = jest.fn().mockReturnValue(mockPromise);
const { result } = renderHook(() => useAsyncRequest(mockRequest));
await act(async () => {
await mockPromise;
});
expect(result.current.loading).toBe(false);
});
it('handle request with response correctly', async () => {
const mockResponse = { code: 'ok' };
const mockPromise = Promise.resolve(mockResponse);
const mockRequest = jest.fn().mockReturnValue(mockPromise);
const { result } = renderHook(() => useAsyncRequest(mockRequest));
await act(async () => {
await mockPromise;
});
expect(result.current.response).toBe(mockResponse);
expect(result.current.loading).toBe(false);
});
it('cancel request correctly', async () => {
const mockCancel = jest.fn();
const mockRequest = { cancel: mockCancel };
const { unmount } = renderHook(() => useAsyncRequest(mockRequest));
unmount();
expect(mockCancel).toBeCalled();
});
});