-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthProvider.test.tsx
More file actions
88 lines (74 loc) · 2.53 KB
/
authProvider.test.tsx
File metadata and controls
88 lines (74 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { act, render, screen, waitFor } from '@testing-library/react';
import { AuthProvider, useAuth } from '../src/AuthProvider';
import { createFetchWithAuth } from '../src/fetchWithAuth';
jest.mock('../src/fetchWithAuth');
jest.mock('@/context/InternalAuthContext', () => ({
InternalAuthProvider: ({ children }: any) => <div>{children}</div>,
}));
// the mock returned fetch function
const mockFetchWithAuthImpl = jest.fn();
// make createFetchWithAuth return our mock function
(createFetchWithAuth as jest.Mock).mockReturnValue(mockFetchWithAuthImpl);
const Consumer = () => {
const auth = useAuth();
return (
<div>
<span data-testid="user">{auth.user ? auth.user.email : 'none'}</span>
<span data-testid="isAuthenticated">{String(auth.isAuthenticated)}</span>
<span data-testid="hasRoleAdmin">{String(auth.hasRole('admin'))}</span>
</div>
);
};
describe('AuthProvider', () => {
const apiHost = 'https://api.example.com/';
beforeEach(() => {
jest.clearAllMocks();
});
it('loads user and token successfully', async () => {
mockFetchWithAuthImpl.mockResolvedValueOnce({
ok: true,
json: async () => ({
user: { id: '1', email: 'test@example.com', phone: '555-1234', roles: ['admin'] },
token: { oneTimeToken: 'abc', expiresAt: '2025-01-01' },
}),
} as any);
await act(async () => {
render(
<AuthProvider apiHost={apiHost}>
<Consumer />
</AuthProvider>
);
});
await waitFor(() => {
expect(screen.getByTestId('user')).toHaveTextContent('test@example.com');
});
expect(screen.getByTestId('isAuthenticated')).toHaveTextContent('true');
expect(screen.getByTestId('hasRoleAdmin')).toHaveTextContent('true');
});
it('logs out if token validation fails (bad response)', async () => {
mockFetchWithAuthImpl.mockResolvedValueOnce({ ok: false } as any);
await act(async () => {
render(
<AuthProvider apiHost={apiHost}>
<Consumer />
</AuthProvider>
);
});
await waitFor(() => {
expect(screen.getByTestId('isAuthenticated')).toHaveTextContent('false');
});
});
it('logs out if token validation throws', async () => {
mockFetchWithAuthImpl.mockRejectedValueOnce(new Error('network down'));
await act(async () => {
render(
<AuthProvider apiHost={apiHost}>
<Consumer />
</AuthProvider>
);
});
await waitFor(() => {
expect(screen.getByTestId('isAuthenticated')).toHaveTextContent('false');
});
});
});