UNPKG

2.38 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import { waitFor, cleanup } from '@testing-library/react';
4import { avPermissionsApi } from '@availity/api-axios';
5import { QueryClient } from 'react-query';
6import renderWithClient from './util';
7import { usePermissions } from '..';
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 = usePermissions({}, { 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('usePermissions', () => {
53 test('should return an error', async () => {
54 avPermissionsApi.getPermissions.mockRejectedValueOnce('An error occurred');
55
56 const { getByText } = renderWithClient(
57 queryClient,
58 <Component log={pushState} />
59 );
60
61 getByText('Status: loading');
62 await waitFor(() => {
63 const el = getByText('Status: error');
64 expect(el).toBeDefined();
65 });
66 await waitFor(() => {
67 const el = getByText('Error: An error occurred');
68 expect(el).toBeDefined();
69 });
70 });
71
72 test('should return permissions', async () => {
73 avPermissionsApi.getPermissions.mockResolvedValueOnce({
74 id: '44',
75 description: 'test',
76 links: { self: { href: 'test.com' } },
77 });
78
79 const { getByText } = renderWithClient(
80 queryClient,
81 <Component log={pushState} />
82 );
83
84 getByText('Status: loading');
85 await waitFor(() => {
86 const el = getByText(
87 `Data: ${JSON.stringify({
88 id: '44',
89 description: 'test',
90 links: { self: { href: 'test.com' } },
91 })}`
92 );
93 expect(el).toBeDefined();
94 });
95 });
96});