Files
solidtime/resources/js/packages/composables/src/apiClient.test.ts
Gregor Vostrak df71051feb Add @solidtime/composables package for logic shared with desktop and the extension (#1430)
* add @solidtime/composables package shared by web, desktop and extension

* bump api to 0.0.8 and require it in composables

* drop the manual composables publish workflow
2026-12-01 17:22:44 +01:00

78 lines
3.1 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest';
import type { AxiosAdapter, InternalAxiosRequestConfig } from 'axios';
import { createApiClient } from '@/packages/api/src/openapi.json.client';
import { withAuthentication } from './apiClient';
function respond(config: InternalAxiosRequestConfig, status: number, data: unknown = {}) {
const response = { data, status, statusText: '', headers: {}, config };
if (status >= 400) {
return Promise.reject(
Object.assign(new Error(`Request failed with status code ${status}`), {
isAxiosError: true,
config,
response,
})
);
}
return Promise.resolve(response);
}
function setup(options: { canRefresh?: boolean; statuses?: number[] } = {}) {
let token = 'old-token';
const statuses = [...(options.statuses ?? [200])];
// Header values as sent, axios reuses the config object for the retry
const requests: unknown[] = [];
const client = createApiClient('https://example.test/api', { validate: 'none' });
client.axios.defaults.adapter = ((config) => {
requests.push(config.headers.Authorization);
return respond(config, statuses.shift() ?? 200, { data: { id: 'me' } });
}) as AxiosAdapter;
const refreshAccessToken = vi.fn(async () => {
token = 'new-token';
});
withAuthentication(client, {
getAccessToken: () => token,
canRefresh: () => options.canRefresh ?? true,
refreshAccessToken,
});
return {
client,
requests,
refreshAccessToken,
setToken: (value: string) => (token = value),
};
}
describe('withAuthentication', () => {
it('reads the token on every request', async () => {
const { client, requests, setToken } = setup();
await client.getMe();
setToken('changed-token');
await client.getMe();
expect(requests).toEqual(['Bearer old-token', 'Bearer changed-token']);
});
it('sets a default timeout', () => {
expect(setup().client.axios.defaults.timeout).toBe(30000);
});
it('refreshes once on a 401 and retries with the new token', async () => {
const { client, requests, refreshAccessToken } = setup({ statuses: [401, 200] });
await expect(client.getMe()).resolves.toEqual({ data: { id: 'me' } });
expect(refreshAccessToken).toHaveBeenCalledOnce();
expect(requests).toEqual(['Bearer old-token', 'Bearer new-token']);
});
it('does not refresh when the app cannot refresh, e.g. with an API token', async () => {
const { client, refreshAccessToken } = setup({ canRefresh: false, statuses: [401] });
await expect(client.getMe()).rejects.toMatchObject({ response: { status: 401 } });
expect(refreshAccessToken).not.toHaveBeenCalled();
});
it('does not refresh twice when the retried request fails again', async () => {
const { client, refreshAccessToken } = setup({ statuses: [401, 401] });
await expect(client.getMe()).rejects.toMatchObject({ response: { status: 401 } });
expect(refreshAccessToken).toHaveBeenCalledOnce();
});
});