Files
zn-ai/tests/host-api-auth.test.ts

61 lines
1.7 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
logout: vi.fn(),
readPersistedAuthToken: vi.fn(),
invoke: vi.fn(),
}));
vi.mock('../src/router/auth-session', () => ({
logout: mocks.logout,
readPersistedAuthToken: mocks.readPersistedAuthToken,
}));
const HOST_API_UNAUTHORIZED_CODE = 'HOST_API_UNAUTHORIZED';
describe('hostApiFetch auth handling', () => {
beforeEach(() => {
vi.resetModules();
mocks.logout.mockReset();
mocks.readPersistedAuthToken.mockReset();
mocks.invoke.mockReset();
mocks.readPersistedAuthToken.mockReturnValue('access-token');
(window as typeof window & { api?: unknown }).api = {
invoke: mocks.invoke,
};
});
afterEach(() => {
delete (window as typeof window & { api?: unknown }).api;
});
it('does not log out when local Host API authentication fails', async () => {
mocks.invoke.mockResolvedValue({
success: false,
ok: false,
status: 401,
code: HOST_API_UNAUTHORIZED_CODE,
error: 'Host API authentication failed',
});
const { hostApiFetch } = await import('../src/lib/host-api');
await expect(hostApiFetch('/api/gateway/status')).rejects.toThrow('Host API authentication failed');
expect(mocks.logout).not.toHaveBeenCalled();
});
it('keeps auth state when upstream business API returns unauthorized', async () => {
mocks.invoke.mockResolvedValue({
success: false,
ok: false,
status: 401,
error: 'Unauthorized',
});
const { hostApiFetch } = await import('../src/lib/host-api');
await expect(hostApiFetch('/api/providers')).rejects.toThrow('Unauthorized');
expect(mocks.logout).not.toHaveBeenCalled();
});
});