test(hooks): finalize mutation test improvements and release acceptance
- Raise use-swipe-gesture mutation score to 66.13% (target 65%+) - Maintain use-reduced-motion mutation score at 76.32% (target 50%+) - Fix use-reduced-motion.ts ESLint set-state-in-effect warning - Add UJ-10 deep searcher journey (category browse → article read → content discovery) - Add 40 new test files (analytics, detail, sections, ui, lib components) - Update test-strategy-plan.md to v2.0 (sync test count to 1591) - Sync README.md with final release metrics Quality gates: TS 0 errors, ESLint 0 errors, 121 suites / 1591 tests passed
This commit is contained in:
1 parent
7c0af54897
commit
602ed6a671
203 files changed
+8338
-81
No files matched your search
@@ -0,0 +1,427 @@
|
||||
// @ts-nocheck
|
||||
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
||||
|
||||
// ─── Mocks ───────────────────────────────────────────────────────────────
|
||||
|
||||
const mockEncrypt = jest.fn<typeof import('./crypto').encrypt>();
|
||||
const mockDecrypt = jest.fn<typeof import('./crypto').decrypt>();
|
||||
|
||||
jest.mock('./crypto', () => ({
|
||||
encrypt: (...args: Parameters<typeof import('./crypto').encrypt>) => mockEncrypt(...args),
|
||||
decrypt: (...args: Parameters<typeof import('./crypto').decrypt>) => mockDecrypt(...args),
|
||||
}));
|
||||
|
||||
// Mock global fetch
|
||||
const mockFetch = jest.fn<typeof global.fetch>();
|
||||
global.fetch = mockFetch as unknown as typeof global.fetch;
|
||||
|
||||
// Mock localStorage
|
||||
const mockStorage: Record<string, string> = {};
|
||||
const mockLocalStorage = {
|
||||
getItem: jest.fn<(key: string) => string | null>().mockImplementation((key: string) => mockStorage[key] ?? null),
|
||||
setItem: jest.fn<(key: string, value: string) => void>().mockImplementation((key: string, value: string) => { mockStorage[key] = value; }),
|
||||
removeItem: jest.fn<(key: string) => void>().mockImplementation((key: string) => { delete mockStorage[key]; }),
|
||||
clear: jest.fn(() => { Object.keys(mockStorage).forEach(k => delete mockStorage[k]); }),
|
||||
length: 0,
|
||||
key: jest.fn<(index: number) => string | null>(),
|
||||
};
|
||||
|
||||
Object.defineProperty(global, 'localStorage', { value: mockLocalStorage, writable: true });
|
||||
|
||||
import { adminApi } from './admin-api';
|
||||
|
||||
function createMockResponse(data: unknown, options: ResponseInit & { headers?: HeadersInit } = {}): Response {
|
||||
return new Response(JSON.stringify(data), {
|
||||
status: 200,
|
||||
...options,
|
||||
headers: { 'Content-Type': 'application/json', ...options.headers },
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockStorage['novalon_admin_token'] = '';
|
||||
mockStorage['novalon_admin_user'] = '';
|
||||
process.env.NEXT_PUBLIC_ENCRYPTION_SECRET = 'test-secret';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.NEXT_PUBLIC_ENCRYPTION_SECRET;
|
||||
});
|
||||
|
||||
// ============ 内部方法测试 ============
|
||||
|
||||
describe('AdminApiClient', () => {
|
||||
describe('request', () => {
|
||||
it('sends GET request without token', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ items: [] }));
|
||||
|
||||
const result = await adminApi.request<{ items: unknown[] }>('/api/admin/models');
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/models',
|
||||
expect.objectContaining({}),
|
||||
);
|
||||
expect(result).toEqual({ items: [] });
|
||||
});
|
||||
|
||||
it('adds Authorization header when token is present', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ success: true }));
|
||||
|
||||
await adminApi.request('/api/admin/items');
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/items',
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ Authorization: 'Bearer test-token' }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('encrypts request body when encryption is available and token present', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockEncrypt.mockResolvedValue('encrypted-data');
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ success: true }));
|
||||
|
||||
await adminApi.request('/api/admin/items', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name: 'test' }),
|
||||
});
|
||||
|
||||
expect(mockEncrypt).toHaveBeenCalled();
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/items',
|
||||
expect.objectContaining({
|
||||
headers: expect.objectContaining({ 'X-Encrypted': 'true' }),
|
||||
body: JSON.stringify({ data: 'encrypted-data' }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not encrypt body when encryption secret is missing', async () => {
|
||||
delete process.env.NEXT_PUBLIC_ENCRYPTION_SECRET;
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ success: true }));
|
||||
|
||||
await adminApi.request('/api/admin/items', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name: 'test' }),
|
||||
});
|
||||
|
||||
expect(mockEncrypt).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('handles 401 by clearing token and redirecting to login', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'expired-token';
|
||||
mockStorage['novalon_admin_user'] = 'admin';
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(null, { status: 401, headers: { 'Content-Type': 'application/json' } }),
|
||||
);
|
||||
|
||||
await expect(adminApi.request('/api/admin/items')).rejects.toThrow('未授权');
|
||||
expect(mockStorage['novalon_admin_token']).toBeUndefined();
|
||||
expect(mockStorage['novalon_admin_user']).toBeUndefined();
|
||||
// Note: window.location.href 重定向在 jsdom 中无法验证(导航未实现)
|
||||
// 该行为在 E2E 测试中验证(e2e/user-journey.spec.ts UJ-03)
|
||||
});
|
||||
|
||||
it('decrypts encrypted response when X-Encrypted header is present', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockDecrypt.mockResolvedValue(JSON.stringify({ secretData: 'decrypted' }));
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
createMockResponse({ data: 'encrypted-response' }, { headers: { 'X-Encrypted': 'true' } }),
|
||||
);
|
||||
|
||||
const result = await adminApi.request<{ secretData: string }>('/api/admin/items');
|
||||
|
||||
expect(mockDecrypt).toHaveBeenCalledWith('encrypted-response');
|
||||
expect(result).toEqual({ secretData: 'decrypted' });
|
||||
});
|
||||
|
||||
it('throws error with non-ok response status', async () => {
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ error: '模型不存在' }), {
|
||||
status: 404,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(adminApi.request('/api/admin/models')).rejects.toThrow('模型不存在');
|
||||
});
|
||||
});
|
||||
|
||||
// ============ 公开 API 方法测试 ============
|
||||
|
||||
describe('login', () => {
|
||||
it('sends POST request with credentials', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ token: 'new-token' }));
|
||||
|
||||
const result = await adminApi.login('admin', 'pass123');
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'admin', password: 'pass123' }),
|
||||
});
|
||||
expect(result).toEqual({ token: 'new-token' });
|
||||
});
|
||||
|
||||
it('throws on login failure', async () => {
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ error: '密码错误' }), {
|
||||
status: 401,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(adminApi.login('admin', 'wrong')).rejects.toThrow('密码错误');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getModels', () => {
|
||||
it('calls request with correct path', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(['model1', 'model2']));
|
||||
|
||||
const result = await adminApi.getModels();
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/models',
|
||||
expect.objectContaining({}),
|
||||
);
|
||||
expect(result).toEqual(['model1', 'model2']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getItems', () => {
|
||||
it('sends query params correctly', async () => {
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
createMockResponse({ items: [], total: 0, page: 1, pageSize: 20, totalPages: 0 }),
|
||||
);
|
||||
|
||||
const result = await adminApi.getItems({ page: 1, pageSize: 20 });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('page=1'),
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('pageSize=20'),
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(result.total).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createItem', () => {
|
||||
it('sends POST with data', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ id: 'new-id' }));
|
||||
|
||||
const result = await adminApi.createItem({ title: 'New Item' });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/items',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: expect.stringContaining('New Item'),
|
||||
}),
|
||||
);
|
||||
expect(result).toEqual({ id: 'new-id' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateItem', () => {
|
||||
it('sends PUT with id and data', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ id: 'item-1', title: 'Updated' }));
|
||||
|
||||
const result = await adminApi.updateItem('item-1', { title: 'Updated' });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('id=item-1'),
|
||||
expect.objectContaining({ method: 'PUT' }),
|
||||
);
|
||||
expect(result).toEqual({ id: 'item-1', title: 'Updated' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteItem', () => {
|
||||
it('sends DELETE with id', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ success: true }));
|
||||
|
||||
const result = await adminApi.deleteItem('item-to-delete');
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('id=item-to-delete'),
|
||||
expect.objectContaining({ method: 'DELETE' }),
|
||||
);
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getZones', () => {
|
||||
it('calls request without pageCode param', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(['zone1']));
|
||||
|
||||
const result = await adminApi.getZones();
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/zones',
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(result).toEqual(['zone1']);
|
||||
});
|
||||
|
||||
it('appends pageCode query param when provided', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse(['zone1']));
|
||||
|
||||
await adminApi.getZones('home');
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/zones?pageCode=home',
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('saveZone', () => {
|
||||
it('sends POST with zone data', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ id: 'zone-1' }));
|
||||
|
||||
const result = await adminApi.saveZone({ name: 'Hero', pageCode: 'home' });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/zones',
|
||||
expect.objectContaining({ method: 'POST' }),
|
||||
);
|
||||
expect(result).toEqual({ id: 'zone-1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMedia', () => {
|
||||
it('calls request without params', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ items: [], total: 0 }));
|
||||
|
||||
const result = await adminApi.getMedia();
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/media?',
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(result.total).toBe(0);
|
||||
});
|
||||
|
||||
it('appends query params when provided', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ items: [], total: 0 }));
|
||||
|
||||
await adminApi.getMedia({ page: 1, type: 'image' });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/page=1.*type=image|type=image.*page=1/),
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadMedia', () => {
|
||||
it('sends FormData with Authorization header', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'upload-token';
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ url: 'https://cdn.example.com/file.jpg' }));
|
||||
|
||||
const file = new File(['content'], 'photo.jpg', { type: 'image/jpeg' });
|
||||
const result = await adminApi.uploadMedia(file);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/media',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: { Authorization: 'Bearer upload-token' },
|
||||
}),
|
||||
);
|
||||
expect(result).toEqual({ url: 'https://cdn.example.com/file.jpg' });
|
||||
});
|
||||
|
||||
it('throws on upload failure', async () => {
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ error: '文件过大' }), {
|
||||
status: 413,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
|
||||
const file = new File(['content'], 'large.jpg', { type: 'image/jpeg' });
|
||||
await expect(adminApi.uploadMedia(file)).rejects.toThrow('文件过大');
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteMedia', () => {
|
||||
it('sends DELETE with media id', async () => {
|
||||
mockFetch.mockResolvedValueOnce(createMockResponse({ success: true }));
|
||||
|
||||
const result = await adminApi.deleteMedia('media-123');
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('id=media-123'),
|
||||
expect.objectContaining({ method: 'DELETE' }),
|
||||
);
|
||||
expect(result).toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStats', () => {
|
||||
it('aggregates stats from models, zones, and items', async () => {
|
||||
mockFetch
|
||||
.mockResolvedValueOnce(createMockResponse(['m1', 'm2', 'm3'])) // getModels
|
||||
.mockResolvedValueOnce(createMockResponse(['z1'])) // getZones
|
||||
.mockResolvedValueOnce(createMockResponse({ items: [], total: 42, page: 1, pageSize: 1, totalPages: 42 })); // getItems
|
||||
|
||||
const stats = await adminApi.getStats();
|
||||
|
||||
expect(stats).toEqual({ models: 3, items: 42, zones: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRoles', () => {
|
||||
it('calls request with correct path', async () => {
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
createMockResponse({
|
||||
roles: [{ code: 'admin', name: '管理员', builtin: true }],
|
||||
permissions: [],
|
||||
models: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await adminApi.getRoles();
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/roles',
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(result.roles).toHaveLength(1);
|
||||
expect(result.roles[0]).toEqual({ code: 'admin', name: '管理员', builtin: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateRolePermissions', () => {
|
||||
it('sends PUT with role code and permissions', async () => {
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
createMockResponse({ roleCode: 'editor', permissions: ['model:read'] }),
|
||||
);
|
||||
|
||||
const result = await adminApi.updateRolePermissions('editor', [
|
||||
{ modelCode: 'model', action: 'read' },
|
||||
]);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'/api/admin/roles',
|
||||
expect.objectContaining({
|
||||
method: 'PUT',
|
||||
body: JSON.stringify({
|
||||
roleCode: 'editor',
|
||||
permissions: [{ modelCode: 'model', action: 'read' }],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(result.roleCode).toBe('editor');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user