Files
vibemake-pcb-studio/qa/unittests/designer/pcb_platform_auth.test.tsx
T
likang 1fde96c05e
CI / typecheck + test + build (push) Has been cancelled
打通vibemake
2026-11-05 16:21:37 +08:00

99 lines
3.9 KiB
TypeScript

// @vitest-environment happy-dom
// SPDX-License-Identifier: GPL-3.0-or-later
import { act, cleanup, render, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
PlatformAuthProvider,
usePlatformAuth,
MOCK,
} from '@ziroeda/designer/src/platform/auth.js';
let auth: ReturnType<typeof usePlatformAuth>;
function Probe(): null {
auth = usePlatformAuth();
return null;
}
const user = { userCode: 'platform-user', email: 'test@example.test', nickname: '测试用户' };
const record = () => ({ token: 'shared-platform-token', user, expiresAt: Date.now() + 86400000 });
const fetcher = vi.fn<typeof fetch>();
const reply = (data: unknown, status = 200, code = 'OK') =>
new Response(JSON.stringify({ code, message: code, data, requestId: 'auth-request' }), {
status,
});
beforeEach(() => {
localStorage.clear();
fetcher.mockReset();
vi.stubGlobal('fetch', fetcher);
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
localStorage.clear();
});
const mount = () =>
render(
<PlatformAuthProvider>
<Probe />
</PlatformAuthProvider>,
);
describe('PCB real shared platform authentication', () => {
it('recognizes the main website vm.auth record and verifies /users/me with the same token', async () => {
expect(MOCK).toBe(false);
localStorage.setItem('vm.auth', JSON.stringify(record()));
fetcher.mockResolvedValueOnce(reply(user));
mount();
await waitFor(() => expect(auth.status).toBe('authenticated'));
expect(auth.record?.user.userCode).toBe(user.userCode);
expect(String(fetcher.mock.calls[0]![0])).toMatch(/\/api\/users\/me$/);
expect(new Headers(fetcher.mock.calls[0]![1]?.headers).get('Authorization')).toBe(
'Bearer shared-platform-token',
);
});
it('signs in with email and captcha, verifies identity, and writes the main website format', async () => {
mount();
await waitFor(() => expect(auth.status).toBe('anonymous'));
fetcher.mockResolvedValueOnce(reply({ token: 'new-platform-token', user, expiresIn: 3600 }));
fetcher.mockResolvedValueOnce(reply(user));
await act(async () => {
await auth.login(' test@example.test ', 'captcha-id', ' abcd ');
});
const [url, init] = fetcher.mock.calls[0]!;
expect(String(url)).toMatch(/\/api\/auth\/login$/);
expect(JSON.parse(String(init?.body))).toEqual({
email: 'test@example.test',
captchaCode: 'captcha-id',
captchaAnswer: 'abcd',
});
const saved = JSON.parse(localStorage.getItem('vm.auth')!);
expect(saved).toMatchObject({ token: 'new-platform-token', user });
expect(saved.expiresAt).toBeGreaterThan(Date.now() + 3590000);
expect(localStorage.getItem('vm.pcb.mock.auth')).toBeNull();
fetcher.mockResolvedValueOnce(reply(null));
await act(async () => {
await auth.logout();
});
expect(String(fetcher.mock.calls[2]![0])).toMatch(/\/api\/auth\/logout$/);
expect(localStorage.getItem('vm.auth')).toBeNull();
});
it('preserves identity on service failure and locks for reauthentication on 401', async () => {
const shared = record();
localStorage.setItem('vm.auth', JSON.stringify(shared));
fetcher.mockRejectedValueOnce(new TypeError('offline'));
mount();
await waitFor(() => expect(auth.status).toBe('error'));
expect(auth.record?.token).toBe(shared.token);
expect(JSON.parse(localStorage.getItem('vm.auth')!).token).toBe(shared.token);
fetcher.mockResolvedValueOnce(reply(null, 401, 'UNAUTHORIZED'));
// Opening the expired-session dialog fetches a new public captcha.
fetcher.mockResolvedValueOnce(
reply({ captchaCode: 'captcha-id', image: 'data:image/png;base64,' }),
);
await act(async () => {
await auth.verify();
});
expect(auth.status).toBe('expired');
expect(auth.loginOpen).toBe(true);
expect(auth.record?.token).toBe(shared.token);
});
});