Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/lib/api/surgeryAPI.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { surgeryAPI } from './surgeryAPI';

describe('surgeryAPI auth handling', () => {
beforeEach(() => {
jest.restoreAllMocks();
localStorage.clear();
});

it('throws a clear error when authToken is missing', async () => {
expect.hasAssertions();

await expect(surgeryAPI.findAll()).rejects.toThrow(
'Authentication required. Please log in to continue.'
);
});

it('throws a clear error when authToken is null string', async () => {
localStorage.setItem('authToken', 'null');
expect.hasAssertions();

await expect(surgeryAPI.findAll()).rejects.toThrow(
'Authentication required. Please log in to continue.'
);
});
});
9 changes: 7 additions & 2 deletions src/lib/api/surgeryAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,14 @@ class SurgeryAPI {

this.api.interceptors.request.use((config) => {
const token = localStorage.getItem('authToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
if (!token || token.trim() === '' || token === 'null') {
throw new Error('Authentication required. Please log in to continue.');
}

config.headers = {
...config.headers,
Authorization: `Bearer ${token}`,
};
return config;
});
}
Expand Down
Loading