Files
back_end_oudelaa/oudelaa_dashboard/tests/auth-clients.test.cjs
boutmoun123 1b753a419a
API Gateway CI / Build, lint, and test (push) Successful in 13m33s
API Gateway CI / Build API Gateway image (push) Successful in 5m43s
feat: sync marketplace dashboard and staging CI
2026-11-02 17:28:58 +03:00

47 lines
2.2 KiB
JavaScript

describe.each([
['superadmin', '../lib/auth/client', 'fetchWithAuth', '/auth/superadmin/refresh'],
['company', '../lib/auth/company-client', 'companyFetch', '/auth/refresh'],
])('%s API client', (_scope, modulePath, method, refreshPath) => {
const originalFetch = global.fetch;
let client;
beforeEach(() => {
jest.resetModules();
client = require(modulePath)[method];
global.fetch = jest.fn();
});
afterEach(() => { global.fetch = originalFetch; });
it('unwraps a response envelope', async () => {
global.fetch.mockResolvedValue(Response.json({ data: { items: [{ id: 'a' }] }, meta: { statusCode: 200 } }));
await expect(client('/items')).resolves.toEqual({ items: [{ id: 'a' }] });
});
it('preserves plain payloads with their own data and meta fields', async () => {
const payload = { data: ['value'], meta: { total: 1 } };
global.fetch.mockResolvedValue(Response.json(payload));
await expect(client('/items')).resolves.toEqual(payload);
});
it('does not treat 401 in an error message as an authentication failure', async () => {
global.fetch.mockResolvedValue(Response.json({ message: 'Item 401 was not found' }, { status: 404 }));
await expect(client('/items')).rejects.toMatchObject({ status: 404 });
expect(global.fetch).toHaveBeenCalledTimes(1);
});
it('refreshes once and replays the request after a real 401', async () => {
global.fetch.mockResolvedValueOnce(Response.json({ message: 'expired' }, { status: 401 }))
.mockResolvedValueOnce(Response.json({ accessToken: 'new-token' }))
.mockResolvedValueOnce(Response.json({ ok: true }));
await expect(client('/items')).resolves.toEqual({ ok: true });
expect(global.fetch.mock.calls[1][0]).toBe(`/api/proxy${refreshPath}`);
expect(global.fetch).toHaveBeenCalledTimes(3);
});
it('does not hide backend unavailability during refresh as an invalid session', async () => {
global.fetch.mockResolvedValueOnce(Response.json({}, { status: 401 }))
.mockResolvedValueOnce(Response.json({ message: 'unavailable' }, { status: 503 }));
await expect(client('/items')).rejects.toMatchObject({ status: 503 });
expect(global.fetch).toHaveBeenCalledTimes(2);
});
});