1 | import React from 'react';
|
2 | import PropTypes from 'prop-types';
|
3 | import { waitFor, cleanup } from '@testing-library/react';
|
4 | import { avRegionsApi } from '@availity/api-axios';
|
5 | import { QueryClient } from 'react-query';
|
6 | import { useCurrentRegion } from '..';
|
7 | import renderWithClient from './util';
|
8 |
|
9 | jest.mock('@availity/api-axios');
|
10 |
|
11 | let queryStates = [];
|
12 | beforeEach(() => {
|
13 | queryStates = [];
|
14 | });
|
15 |
|
16 | const queryClient = new QueryClient();
|
17 |
|
18 | afterEach(() => {
|
19 | jest.clearAllMocks();
|
20 | cleanup();
|
21 | queryClient.clear();
|
22 | queryStates = [];
|
23 | });
|
24 |
|
25 | const pushState = (state) => {
|
26 | queryStates.push(state);
|
27 | };
|
28 |
|
29 | const Component = ({ log }) => {
|
30 |
|
31 |
|
32 | const state = useCurrentRegion({ cacheTime: 0, retry: false });
|
33 |
|
34 |
|
35 | if (log) log(state);
|
36 |
|
37 | const { data, error, status } = state;
|
38 |
|
39 | return (
|
40 | <div>
|
41 | <h1>Status: {status}</h1>
|
42 | <h1>Data: {JSON.stringify(data)}</h1>
|
43 | <h1>Error: {error}</h1>
|
44 | </div>
|
45 | );
|
46 | };
|
47 |
|
48 | Component.propTypes = {
|
49 | log: PropTypes.func,
|
50 | };
|
51 |
|
52 | describe('useCurrentRegion', () => {
|
53 | test('handle error', async () => {
|
54 | avRegionsApi.getCurrentRegion.mockRejectedValueOnce('An error occurred');
|
55 | const { getByText } = renderWithClient(
|
56 | queryClient,
|
57 | <Component log={pushState} />
|
58 | );
|
59 |
|
60 | getByText('Status: loading');
|
61 | await waitFor(() => {
|
62 | const el = getByText('Status: error');
|
63 | expect(el).toBeDefined();
|
64 | });
|
65 | await waitFor(() => {
|
66 | const el = getByText('Error: An error occurred');
|
67 | expect(el).toBeDefined();
|
68 | });
|
69 | });
|
70 |
|
71 | test('handle success', async () => {
|
72 | avRegionsApi.getCurrentRegion.mockResolvedValueOnce({
|
73 | config: { polling: false },
|
74 | data: {
|
75 | regions: [
|
76 | {
|
77 | id: 'FL',
|
78 | value: 'Florida',
|
79 | },
|
80 | ],
|
81 | },
|
82 | status: 200,
|
83 | statusText: 'Ok',
|
84 | });
|
85 |
|
86 | const { getByText } = renderWithClient(
|
87 | queryClient,
|
88 | <Component log={pushState} />
|
89 | );
|
90 |
|
91 | getByText('Status: loading');
|
92 | await waitFor(() => {
|
93 | const el = getByText(
|
94 | `Data: ${JSON.stringify({
|
95 | code: 'FL',
|
96 | value: 'Florida',
|
97 | })}`
|
98 | );
|
99 | expect(el).toBeDefined();
|
100 | });
|
101 | });
|
102 | });
|