import * as React from 'react'; import expect from 'expect'; import { waitFor, render, screen } from '@testing-library/react'; import { CoreAdminContext } from '../core/CoreAdminContext'; import useAuthState from './useAuthState'; import { QueryClient } from '@tanstack/react-query'; const UseAuth = (authParams: any) => { const state = useAuthState(authParams); return (
{state.isPending && 'LOADING'} AUTHENTICATED: {state.authenticated?.toString()}
); }; describe('useAuthState', () => { it('should return authenticated by default after a tick', async () => { render( ); await waitFor(() => { expect(screen.queryByText('LOADING')).toBeNull(); }); screen.getByText('AUTHENTICATED: true'); }); it('should return an error after a tick if the auth fails', async () => { const authProvider = { login: () => Promise.reject('bad method'), logout: () => Promise.reject('bad method'), checkAuth: () => Promise.reject('failed'), checkError: () => Promise.reject('bad method'), getPermissions: () => Promise.reject('bad method'), }; render( ); await waitFor(() => { expect(screen.queryByText('LOADING')).toBeNull(); }); screen.getByText('AUTHENTICATED: false'); }); it('should abort the request if the query is canceled', async () => { const abort = jest.fn(); const authProvider = { checkAuth: jest.fn( ({ signal }) => new Promise(() => { signal.addEventListener('abort', () => { abort(signal.reason); }); }) ) as any, } as any; const queryClient = new QueryClient(); render( ); await waitFor(() => { expect(authProvider.checkAuth).toHaveBeenCalled(); }); queryClient.cancelQueries({ queryKey: ['auth', 'checkAuth'], }); await waitFor(() => { expect(abort).toHaveBeenCalled(); }); }); });