UNPKG

2.42 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import { waitFor, cleanup } from '@testing-library/react';
4import { avRegionsApi } from '@availity/api-axios';
5import { QueryClient } from 'react-query';
6import { useCurrentRegion } from '..';
7import renderWithClient from './util';
8
9jest.mock('@availity/api-axios');
10
11let queryStates = [];
12beforeEach(() => {
13 queryStates = [];
14});
15
16const queryClient = new QueryClient();
17
18afterEach(() => {
19 jest.clearAllMocks();
20 cleanup();
21 queryClient.clear();
22 queryStates = [];
23});
24
25const pushState = (state) => {
26 queryStates.push(state);
27};
28
29const Component = ({ log }) => {
30 // Mirror testing methods from react-query instead of relying on timing or booleans
31 // https://github.com/tannerlinsley/react-query/blob/master/src/react/tests/useQuery.test.tsx
32 const state = useCurrentRegion({ cacheTime: 0, retry: false });
33
34 // not directly used in assertions here, but useful for debugging purposes
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
48Component.propTypes = {
49 log: PropTypes.func,
50};
51
52describe('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});