UNPKG

2.43 kBJavaScriptView Raw
1import React from 'react';
2import PropTypes from 'prop-types';
3import { waitFor, cleanup } from '@testing-library/react';
4import { avUserApi } from '@availity/api-axios';
5import { QueryClient } from 'react-query';
6import { useCurrentUser } 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 = useCurrentUser({ 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('useCurrentUser', () => {
53 test('should set error on rejected promise', async () => {
54 avUserApi.me.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 user', async () => {
73 avUserApi.me.mockResolvedValueOnce({
74 id: 'aka12345',
75 userId: 'testExample',
76 akaname: 'aka12345',
77 lastName: 'Last',
78 firstName: 'First',
79 });
80
81 const { getByText } = renderWithClient(
82 queryClient,
83 <Component log={pushState} />
84 );
85
86 getByText('Status: loading');
87 await waitFor(() => {
88 const el = getByText(
89 `Data: ${JSON.stringify({
90 id: 'aka12345',
91 userId: 'testExample',
92 akaname: 'aka12345',
93 lastName: 'Last',
94 firstName: 'First',
95 })}`
96 );
97 expect(el).toBeDefined();
98 });
99 });
100});