Compare commits
9 Commits
feat/admin
...
feat/testi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3d7f1d24c | ||
|
|
cacb9e0c9b | ||
|
|
39be02e1ca | ||
|
|
bef2dc57b5 | ||
|
|
e00f9e197c | ||
|
|
bfb71333a4 | ||
|
|
144dcc60ec | ||
|
|
aeb563d037 | ||
|
|
85a3d274e6 |
51
tests/helpers/build-admin-test-app.ts
Normal file
51
tests/helpers/build-admin-test-app.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import Fastify, { FastifyInstance } from 'fastify';
|
||||
import { AppError } from '../../src/utils/errors.js';
|
||||
import { adminQuestionsRoutes } from '../../src/routes/admin/questions.js';
|
||||
import type { MockDb } from '../test-utils.js';
|
||||
import { createMockDb } from '../test-utils.js';
|
||||
|
||||
const mockAdminUser = { id: 'admin-1', email: 'admin@test.com' };
|
||||
|
||||
/**
|
||||
* Build a minimal Fastify app for admin route integration tests.
|
||||
* Bypasses real auth - preHandlers set req.user to mock admin.
|
||||
*/
|
||||
export async function buildAdminTestApp(mockDb?: MockDb): Promise<FastifyInstance> {
|
||||
const db = mockDb ?? createMockDb();
|
||||
|
||||
const app = Fastify({
|
||||
logger: false,
|
||||
requestIdHeader: 'x-request-id',
|
||||
requestIdLogLabel: 'requestId',
|
||||
});
|
||||
|
||||
app.setErrorHandler((err: unknown, _request, reply) => {
|
||||
const error = err as Error & { statusCode?: number; validation?: unknown };
|
||||
if (err instanceof AppError) {
|
||||
return reply.status(err.statusCode).send(err.toJSON());
|
||||
}
|
||||
if (error.validation) {
|
||||
return reply.status(422).send({
|
||||
error: { code: 'VALIDATION_ERROR', message: 'Validation failed', details: error.validation },
|
||||
});
|
||||
}
|
||||
return reply.status(500).send({ error: { code: 'INTERNAL_ERROR', message: error.message } });
|
||||
});
|
||||
|
||||
app.decorate('db', db);
|
||||
app.decorate('rateLimitOptions', {
|
||||
apiAuthed: { max: 100, timeWindow: '1 minute' },
|
||||
});
|
||||
app.decorateRequest('user', undefined);
|
||||
app.decorate('authenticate', async (req: { user?: { id: string; email: string } }) => {
|
||||
req.user = mockAdminUser;
|
||||
});
|
||||
app.decorate('authenticateAdmin', async (req: { user?: { id: string; email: string } }) => {
|
||||
if (!req.user) req.user = mockAdminUser;
|
||||
(req.user as { role?: string }).role = 'admin';
|
||||
});
|
||||
|
||||
await app.register(adminQuestionsRoutes, { prefix: '/admin' });
|
||||
|
||||
return app;
|
||||
}
|
||||
46
tests/helpers/build-test-app.ts
Normal file
46
tests/helpers/build-test-app.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import Fastify, { FastifyInstance } from 'fastify';
|
||||
import { AppError } from '../../src/utils/errors.js';
|
||||
import { authRoutes } from '../../src/routes/auth.js';
|
||||
import type { MockDb } from '../test-utils.js';
|
||||
import { createMockDb } from '../test-utils.js';
|
||||
|
||||
/**
|
||||
* Build a minimal Fastify app for auth route integration tests.
|
||||
* Uses mock db and rate limit options (no actual rate limiting).
|
||||
*/
|
||||
export async function buildAuthTestApp(mockDb?: MockDb): Promise<FastifyInstance> {
|
||||
const db = mockDb ?? createMockDb();
|
||||
|
||||
const app = Fastify({
|
||||
logger: false,
|
||||
requestIdHeader: 'x-request-id',
|
||||
requestIdLogLabel: 'requestId',
|
||||
});
|
||||
|
||||
app.setErrorHandler((err: unknown, request, reply) => {
|
||||
const error = err as Error & { statusCode?: number; validation?: unknown };
|
||||
if (err instanceof AppError) {
|
||||
return reply.status(err.statusCode).send(err.toJSON());
|
||||
}
|
||||
if (error.validation) {
|
||||
return reply.status(422).send({
|
||||
error: { code: 'VALIDATION_ERROR', message: 'Validation failed', details: error.validation },
|
||||
});
|
||||
}
|
||||
return reply.status(500).send({ error: { code: 'INTERNAL_ERROR', message: error.message } });
|
||||
});
|
||||
|
||||
app.decorate('db', db);
|
||||
app.decorate('rateLimitOptions', {
|
||||
login: { max: 100, timeWindow: '1 minute' },
|
||||
register: { max: 100, timeWindow: '1 hour' },
|
||||
forgotPassword: { max: 100, timeWindow: '1 hour' },
|
||||
verifyEmail: { max: 100, timeWindow: '15 minutes' },
|
||||
apiAuthed: { max: 100, timeWindow: '1 minute' },
|
||||
apiGuest: { max: 100, timeWindow: '1 minute' },
|
||||
});
|
||||
|
||||
await app.register(authRoutes, { prefix: '/auth' });
|
||||
|
||||
return app;
|
||||
}
|
||||
140
tests/integration/admin.routes.test.ts
Normal file
140
tests/integration/admin.routes.test.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { buildAdminTestApp } from '../helpers/build-admin-test-app.js';
|
||||
import {
|
||||
createMockDb,
|
||||
selectChainOrderedLimitOffset,
|
||||
selectChainWhere,
|
||||
updateChainReturning,
|
||||
insertChain,
|
||||
} from '../test-utils.js';
|
||||
|
||||
describe('Admin routes integration', () => {
|
||||
let app: Awaited<ReturnType<typeof buildAdminTestApp>>;
|
||||
let mockDb: ReturnType<typeof createMockDb>;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
mockDb = createMockDb();
|
||||
app = await buildAdminTestApp(mockDb as never);
|
||||
});
|
||||
|
||||
describe('GET /admin/questions/pending', () => {
|
||||
it('returns pending questions list', async () => {
|
||||
const pendingQuestions = [
|
||||
{
|
||||
id: 'q-1',
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
type: 'single_choice',
|
||||
questionText: 'Test question?',
|
||||
options: [{ key: 'a', text: 'A' }],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'Exp',
|
||||
source: 'manual',
|
||||
createdAt: new Date(),
|
||||
},
|
||||
];
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChainOrderedLimitOffset(pendingQuestions))
|
||||
.mockReturnValueOnce(selectChainWhere([{ count: 1 }]));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/admin/questions/pending',
|
||||
headers: { authorization: 'Bearer any-token' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.questions).toHaveLength(1);
|
||||
expect(body.questions[0].questionText).toBe('Test question?');
|
||||
expect(body.total).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /admin/questions/:questionId/approve', () => {
|
||||
it('returns 204 on success', async () => {
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChainReturning([{ id: 'q-1' }])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111/approve',
|
||||
headers: { authorization: 'Bearer any-token' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
|
||||
it('returns 404 when question not found', async () => {
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChainReturning([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111/approve',
|
||||
headers: { authorization: 'Bearer any-token' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /admin/questions/:questionId/reject', () => {
|
||||
it('returns 204 on success', async () => {
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChainReturning([{ id: 'q-1' }])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111/reject',
|
||||
headers: { authorization: 'Bearer any-token' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /admin/questions/:questionId', () => {
|
||||
it('returns updated question', async () => {
|
||||
const updatedQuestion = {
|
||||
id: 'q-1',
|
||||
stack: 'js',
|
||||
level: 'intermediate',
|
||||
type: 'single_choice',
|
||||
questionText: 'Updated?',
|
||||
options: [{ key: 'a', text: 'A' }],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'Updated exp',
|
||||
source: 'manual',
|
||||
createdAt: new Date(),
|
||||
};
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChainReturning([updatedQuestion])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'PATCH',
|
||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111',
|
||||
headers: { authorization: 'Bearer any-token' },
|
||||
payload: { questionText: 'Updated?', explanation: 'Updated exp' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.questionText).toBe('Updated?');
|
||||
});
|
||||
});
|
||||
});
|
||||
265
tests/integration/auth.routes.test.ts
Normal file
265
tests/integration/auth.routes.test.ts
Normal file
@@ -0,0 +1,265 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { buildAuthTestApp } from '../helpers/build-test-app.js';
|
||||
import {
|
||||
createMockDb,
|
||||
selectChain,
|
||||
insertChain,
|
||||
updateChain,
|
||||
deleteChain,
|
||||
} from '../test-utils.js';
|
||||
|
||||
vi.mock('../../src/utils/password.js', () => ({
|
||||
hashPassword: vi.fn().mockResolvedValue('hashed-password'),
|
||||
verifyPassword: vi.fn().mockResolvedValue(true),
|
||||
}));
|
||||
|
||||
vi.mock('../../src/utils/jwt.js', () => ({
|
||||
signAccessToken: vi.fn().mockResolvedValue('access-token'),
|
||||
signRefreshToken: vi.fn().mockResolvedValue('refresh-token'),
|
||||
verifyToken: vi.fn(),
|
||||
isRefreshPayload: vi.fn(),
|
||||
hashToken: vi.fn((t: string) => `hash-${t}`),
|
||||
}));
|
||||
|
||||
vi.mock('node:crypto', () => ({
|
||||
randomBytes: vi.fn(() => ({ toString: () => 'abc123' })),
|
||||
randomUUID: vi.fn(() => 'uuid-session-1'),
|
||||
}));
|
||||
|
||||
import { isRefreshPayload, verifyToken } from '../../src/utils/jwt.js';
|
||||
|
||||
describe('Auth routes integration', () => {
|
||||
let app: Awaited<ReturnType<typeof buildAuthTestApp>>;
|
||||
let mockDb: ReturnType<typeof createMockDb>;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
mockDb = createMockDb();
|
||||
app = await buildAuthTestApp(mockDb as never);
|
||||
});
|
||||
|
||||
describe('POST /auth/register', () => {
|
||||
it('returns 201 with userId and verificationCode when registration succeeds', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([]))
|
||||
.mockReturnValueOnce(selectChain([]));
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(insertChain([{ id: 'user-123' }]))
|
||||
.mockReturnValueOnce(insertChain([]));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/register',
|
||||
payload: {
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
nickname: 'tester',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(201);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.userId).toBe('user-123');
|
||||
expect(body.message).toContain('verify your email');
|
||||
expect(body.verificationCode).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns 409 when email is already taken', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 'existing', email: 'test@example.com' }])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/register',
|
||||
payload: {
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
nickname: 'tester',
|
||||
},
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(409);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.error?.code).toBe('EMAIL_TAKEN');
|
||||
});
|
||||
|
||||
it('returns 422 when validation fails', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/register',
|
||||
payload: {
|
||||
email: 'short',
|
||||
password: '123', // too short
|
||||
nickname: 'x', // too short
|
||||
},
|
||||
});
|
||||
|
||||
expect([400, 422]).toContain(res.statusCode);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.error?.code ?? body.error).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /auth/login', () => {
|
||||
it('returns tokens when credentials are valid', async () => {
|
||||
const mockUser = {
|
||||
id: 'user-1',
|
||||
email: 'test@example.com',
|
||||
passwordHash: 'hashed',
|
||||
};
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([mockUser])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/login',
|
||||
payload: { email: 'test@example.com', password: 'password123' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.accessToken).toBe('access-token');
|
||||
expect(body.refreshToken).toBe('refresh-token');
|
||||
});
|
||||
|
||||
it('returns 401 when credentials are invalid', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/login',
|
||||
payload: { email: 'unknown@example.com', password: 'wrong' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /auth/logout', () => {
|
||||
it('returns 204 on success', async () => {
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/logout',
|
||||
payload: { refreshToken: 'some-token' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(204);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /auth/refresh', () => {
|
||||
it('returns new tokens when refresh token is valid', async () => {
|
||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
||||
sub: 'user-1',
|
||||
sid: 'sid-1',
|
||||
type: 'refresh',
|
||||
} as never);
|
||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(true);
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([{ id: 'sess-1', userId: 'user-1' }]))
|
||||
.mockReturnValueOnce(selectChain([{ id: 'user-1', email: 'test@example.com' }]));
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/refresh',
|
||||
payload: { refreshToken: 'valid-refresh-token' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.accessToken).toBe('access-token');
|
||||
expect(body.refreshToken).toBe('refresh-token');
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /auth/verify-email', () => {
|
||||
it('returns success when code is valid', async () => {
|
||||
const mockCode = {
|
||||
id: 'code-1',
|
||||
userId: 'user-1',
|
||||
code: 'ABC123',
|
||||
expiresAt: new Date(Date.now() + 60000),
|
||||
};
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([mockCode]))
|
||||
.mockReturnValueOnce(selectChain([{ id: 'user-1', emailVerifiedAt: null }]));
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChain([{ id: 'user-1' }])
|
||||
);
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/verify-email',
|
||||
payload: { userId: 'user-1', code: 'ABC123' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /auth/forgot-password', () => {
|
||||
it('returns 200 with generic message', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 'user-1', email: 'test@example.com' }])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/forgot-password',
|
||||
payload: { email: 'test@example.com' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /auth/reset-password', () => {
|
||||
it('returns 200 when token is valid', async () => {
|
||||
const mockRecord = {
|
||||
id: 'rec-1',
|
||||
userId: 'user-1',
|
||||
expiresAt: new Date(Date.now() + 60000),
|
||||
};
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([mockRecord])
|
||||
);
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChain([{ id: 'user-1' }])
|
||||
);
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/reset-password',
|
||||
payload: { token: 'valid-token', newPassword: 'newPassword123' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
304
tests/services/auth.service.test.ts
Normal file
304
tests/services/auth.service.test.ts
Normal file
@@ -0,0 +1,304 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { AuthService } from '../../src/services/auth/auth.service.js';
|
||||
import {
|
||||
createMockDb,
|
||||
selectChain,
|
||||
insertChain,
|
||||
updateChain,
|
||||
deleteChain,
|
||||
} from '../test-utils.js';
|
||||
|
||||
vi.mock('../../src/utils/password.js', () => ({
|
||||
hashPassword: vi.fn().mockResolvedValue('hashed-password'),
|
||||
verifyPassword: vi.fn().mockResolvedValue(true),
|
||||
}));
|
||||
|
||||
vi.mock('../../src/utils/jwt.js', () => ({
|
||||
signAccessToken: vi.fn().mockResolvedValue('access-token'),
|
||||
signRefreshToken: vi.fn().mockResolvedValue('refresh-token'),
|
||||
verifyToken: vi.fn(),
|
||||
isRefreshPayload: vi.fn(),
|
||||
hashToken: vi.fn((t: string) => `hash-${t}`),
|
||||
}));
|
||||
|
||||
vi.mock('node:crypto', () => ({
|
||||
randomBytes: vi.fn(() => ({
|
||||
toString: () => 'abc123',
|
||||
})),
|
||||
randomUUID: vi.fn(() => 'uuid-session-1'),
|
||||
}));
|
||||
|
||||
import { hashPassword, verifyPassword } from '../../src/utils/password.js';
|
||||
import { signAccessToken, signRefreshToken, verifyToken, isRefreshPayload } from '../../src/utils/jwt.js';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let mockDb: ReturnType<typeof createMockDb>;
|
||||
let authService: AuthService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockDb = createMockDb();
|
||||
authService = new AuthService(mockDb as never);
|
||||
});
|
||||
|
||||
describe('register', () => {
|
||||
it('registers a new user when email and nickname are available', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([]))
|
||||
.mockReturnValueOnce(selectChain([]));
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(insertChain([{ id: 'user-123' }]))
|
||||
.mockReturnValueOnce(insertChain([]));
|
||||
|
||||
const result = await authService.register({
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
nickname: 'tester',
|
||||
});
|
||||
|
||||
expect(result.userId).toBe('user-123');
|
||||
expect(result.verificationCode).toBeDefined();
|
||||
expect(hashPassword).toHaveBeenCalledWith('password123');
|
||||
});
|
||||
|
||||
it('throws when email is already taken', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 'existing', email: 'test@example.com' }])
|
||||
);
|
||||
|
||||
await expect(
|
||||
authService.register({
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
nickname: 'tester',
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'EMAIL_TAKEN' });
|
||||
});
|
||||
|
||||
it('throws when nickname is already taken', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([]))
|
||||
.mockReturnValueOnce(selectChain([{ id: 'existing', nickname: 'tester' }]));
|
||||
|
||||
await expect(
|
||||
authService.register({
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
nickname: 'tester',
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'NICKNAME_TAKEN' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('login', () => {
|
||||
it('returns tokens when credentials are valid', async () => {
|
||||
const mockUser = {
|
||||
id: 'user-1',
|
||||
email: 'test@example.com',
|
||||
passwordHash: 'hashed',
|
||||
};
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([mockUser])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const result = await authService.login({
|
||||
email: 'test@example.com',
|
||||
password: 'password123',
|
||||
});
|
||||
|
||||
expect(result.accessToken).toBe('access-token');
|
||||
expect(result.refreshToken).toBe('refresh-token');
|
||||
expect(verifyPassword).toHaveBeenCalledWith('hashed', 'password123');
|
||||
expect(signAccessToken).toHaveBeenCalled();
|
||||
expect(signRefreshToken).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws when user not found', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([])
|
||||
);
|
||||
|
||||
await expect(
|
||||
authService.login({ email: 'nonexistent@example.com', password: 'x' })
|
||||
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
|
||||
});
|
||||
|
||||
it('throws when password is wrong', async () => {
|
||||
vi.mocked(verifyPassword).mockResolvedValueOnce(false);
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 'user-1', email: 'test@example.com', passwordHash: 'hashed' }])
|
||||
);
|
||||
|
||||
await expect(
|
||||
authService.login({ email: 'test@example.com', password: 'wrong' })
|
||||
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('logout', () => {
|
||||
it('deletes session by refresh token hash', async () => {
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
|
||||
await authService.logout('some-refresh-token');
|
||||
|
||||
expect(mockDb.delete).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('refresh', () => {
|
||||
it('returns new tokens when refresh token is valid', async () => {
|
||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
||||
sub: 'user-1',
|
||||
sid: 'sid-1',
|
||||
type: 'refresh',
|
||||
} as never);
|
||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(true);
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 'sess-1', userId: 'user-1' }])
|
||||
);
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 'user-1', email: 'test@example.com' }])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const result = await authService.refresh({
|
||||
refreshToken: 'valid-refresh-token',
|
||||
});
|
||||
|
||||
expect(result.accessToken).toBe('access-token');
|
||||
expect(result.refreshToken).toBe('refresh-token');
|
||||
});
|
||||
|
||||
it('throws when token is not a refresh payload', async () => {
|
||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
||||
sub: 'user-1',
|
||||
type: 'access',
|
||||
} as never);
|
||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(false);
|
||||
|
||||
await expect(
|
||||
authService.refresh({ refreshToken: 'access-token' })
|
||||
).rejects.toMatchObject({ message: expect.stringContaining('Invalid refresh token') });
|
||||
});
|
||||
|
||||
it('throws when session not found', async () => {
|
||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
||||
sub: 'user-1',
|
||||
sid: 'sid-1',
|
||||
type: 'refresh',
|
||||
} as never);
|
||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(true);
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([])
|
||||
);
|
||||
|
||||
await expect(
|
||||
authService.refresh({ refreshToken: 'invalid-or-expired' })
|
||||
).rejects.toMatchObject({ code: 'INVALID_REFRESH_TOKEN' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('verifyEmail', () => {
|
||||
it('throws when verification code is invalid', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([])
|
||||
);
|
||||
|
||||
await expect(
|
||||
authService.verifyEmail('user-1', 'WRONG')
|
||||
).rejects.toMatchObject({ code: 'INVALID_CODE' });
|
||||
});
|
||||
|
||||
it('updates user and deletes code when valid', async () => {
|
||||
const mockCode = {
|
||||
id: 'code-1',
|
||||
userId: 'user-1',
|
||||
code: 'ABC123',
|
||||
expiresAt: new Date(Date.now() + 60000),
|
||||
};
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([mockCode]))
|
||||
.mockReturnValueOnce(selectChain([{ id: 'user-1', emailVerifiedAt: null }]));
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChain([{ id: 'user-1' }])
|
||||
);
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
|
||||
await authService.verifyEmail('user-1', 'ABC123');
|
||||
|
||||
expect(mockDb.update).toHaveBeenCalled();
|
||||
expect(mockDb.delete).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('forgotPassword', () => {
|
||||
it('returns empty token when user not found', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([])
|
||||
);
|
||||
|
||||
const result = await authService.forgotPassword('unknown@example.com');
|
||||
|
||||
expect(result.token).toBe('');
|
||||
expect(result.expiresAt).toBeInstanceOf(Date);
|
||||
});
|
||||
|
||||
it('returns token when user exists', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 'user-1', email: 'test@example.com' }])
|
||||
);
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
insertChain([])
|
||||
);
|
||||
|
||||
const result = await authService.forgotPassword('test@example.com');
|
||||
|
||||
expect(result.token).toBeDefined();
|
||||
expect(result.token).not.toBe('');
|
||||
expect(result.expiresAt).toBeInstanceOf(Date);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resetPassword', () => {
|
||||
it('throws when token is invalid', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([])
|
||||
);
|
||||
|
||||
await expect(
|
||||
authService.resetPassword('invalid-token', 'newPassword123')
|
||||
).rejects.toMatchObject({ code: 'INVALID_RESET_TOKEN' });
|
||||
});
|
||||
|
||||
it('updates password when token is valid', async () => {
|
||||
const mockRecord = { id: 'rec-1', userId: 'user-1', expiresAt: new Date(Date.now() + 60000) };
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([mockRecord])
|
||||
);
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChain([{ id: 'user-1' }])
|
||||
);
|
||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
deleteChain()
|
||||
);
|
||||
|
||||
await authService.resetPassword('valid-token', 'newPassword123');
|
||||
|
||||
expect(hashPassword).toHaveBeenCalledWith('newPassword123');
|
||||
expect(mockDb.update).toHaveBeenCalled();
|
||||
expect(mockDb.delete).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
224
tests/services/llm.service.test.ts
Normal file
224
tests/services/llm.service.test.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('../../src/config/env.js', () => ({
|
||||
env: {
|
||||
LLM_BASE_URL: 'http://test',
|
||||
LLM_MODEL: 'test-model',
|
||||
LLM_FALLBACK_MODEL: 'fallback-model',
|
||||
LLM_API_KEY: 'key',
|
||||
LLM_TIMEOUT_MS: 5000,
|
||||
LLM_TEMPERATURE: 0.7,
|
||||
LLM_MAX_TOKENS: 2048,
|
||||
LLM_MAX_RETRIES: 1,
|
||||
LLM_RETRY_DELAY_MS: 10,
|
||||
},
|
||||
}));
|
||||
|
||||
import { LlmService } from '../../src/services/llm/llm.service.js';
|
||||
|
||||
const mockConfig = {
|
||||
baseUrl: 'http://llm.test/v1',
|
||||
model: 'test-model',
|
||||
fallbackModel: 'fallback-model',
|
||||
apiKey: 'test-key',
|
||||
timeoutMs: 5000,
|
||||
temperature: 0.7,
|
||||
maxTokens: 2048,
|
||||
maxRetries: 1,
|
||||
retryDelayMs: 10,
|
||||
};
|
||||
|
||||
const validQuestionsJson = JSON.stringify({
|
||||
questions: [
|
||||
{
|
||||
questionText: 'What is 2+2?',
|
||||
type: 'single_choice',
|
||||
options: [{ key: 'a', text: '4' }, { key: 'b', text: '3' }],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'Basic math',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
describe('LlmService', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch = vi.fn();
|
||||
vi.stubGlobal('fetch', mockFetch);
|
||||
});
|
||||
|
||||
describe('chat', () => {
|
||||
it('returns content from LLM response', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: 'Hello!' } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService(mockConfig);
|
||||
const result = await service.chat([
|
||||
{ role: 'user', content: 'Hi' },
|
||||
]);
|
||||
|
||||
expect(result).toBe('Hello!');
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
'http://llm.test/v1/chat/completions',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: expect.objectContaining({
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer test-key',
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('chatWithMeta', () => {
|
||||
it('returns content and model name', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: 'Response' } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService(mockConfig);
|
||||
const result = await service.chatWithMeta([{ role: 'user', content: 'Q' }]);
|
||||
|
||||
expect(result.content).toBe('Response');
|
||||
expect(result.model).toBe('test-model');
|
||||
});
|
||||
|
||||
it('retries on failure then succeeds', async () => {
|
||||
mockFetch
|
||||
.mockRejectedValueOnce(new Error('Network error'))
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: 'Retry OK' } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService({ ...mockConfig, maxRetries: 1 });
|
||||
const result = await service.chatWithMeta([{ role: 'user', content: 'Q' }]);
|
||||
|
||||
expect(result.content).toBe('Retry OK');
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('falls back to fallbackModel when primary fails', async () => {
|
||||
// Primary model: 2 attempts (initial + 1 retry), both fail
|
||||
mockFetch
|
||||
.mockResolvedValueOnce({ ok: false, status: 500, statusText: 'Error', text: () => Promise.resolve('') })
|
||||
.mockResolvedValueOnce({ ok: false, status: 500, statusText: 'Error', text: () => Promise.resolve('') })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: 'Fallback OK' } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService(mockConfig);
|
||||
const result = await service.chatWithMeta([{ role: 'user', content: 'Q' }]);
|
||||
|
||||
expect(result.content).toBe('Fallback OK');
|
||||
expect(result.model).toBe('fallback-model');
|
||||
});
|
||||
|
||||
it('throws when all attempts fail', async () => {
|
||||
mockFetch.mockRejectedValue(new Error('Network error'));
|
||||
|
||||
const service = new LlmService({ ...mockConfig, maxRetries: 0 });
|
||||
await expect(
|
||||
service.chatWithMeta([{ role: 'user', content: 'Q' }])
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateQuestions', () => {
|
||||
it('returns validated questions with meta', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: validQuestionsJson } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService(mockConfig);
|
||||
const result = await service.generateQuestions({
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
count: 1,
|
||||
});
|
||||
|
||||
expect(result.questions).toHaveLength(1);
|
||||
expect(result.questions[0].questionText).toBe('What is 2+2?');
|
||||
expect(result.questions[0].stack).toBe('js');
|
||||
expect(result.questions[0].level).toBe('beginner');
|
||||
expect(result.meta.llmModel).toBe('test-model');
|
||||
expect(result.meta.promptHash).toBeDefined();
|
||||
expect(result.meta.generationTimeMs).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it('extracts JSON from markdown code block', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: '```json\n' + validQuestionsJson + '\n```' } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService(mockConfig);
|
||||
const result = await service.generateQuestions({
|
||||
stack: 'ts',
|
||||
level: 'intermediate',
|
||||
count: 1,
|
||||
});
|
||||
|
||||
expect(result.questions).toHaveLength(1);
|
||||
expect(result.questions[0].type).toBe('single_choice');
|
||||
});
|
||||
|
||||
it('throws when response validation fails', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: '{"invalid": "response"}' } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService(mockConfig);
|
||||
await expect(
|
||||
service.generateQuestions({ stack: 'js', level: 'beginner', count: 1 })
|
||||
).rejects.toThrow('LLM response validation failed');
|
||||
});
|
||||
|
||||
it('throws when single_choice has no options', async () => {
|
||||
const invalidJson = JSON.stringify({
|
||||
questions: [
|
||||
{
|
||||
questionText: 'Q?',
|
||||
type: 'single_choice',
|
||||
options: [],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'e',
|
||||
},
|
||||
],
|
||||
});
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({
|
||||
choices: [{ message: { content: invalidJson } }],
|
||||
}),
|
||||
});
|
||||
|
||||
const service = new LlmService(mockConfig);
|
||||
await expect(
|
||||
service.generateQuestions({ stack: 'js', level: 'beginner', count: 1 })
|
||||
).rejects.toThrow('Question validation failed');
|
||||
});
|
||||
});
|
||||
});
|
||||
117
tests/services/question.service.test.ts
Normal file
117
tests/services/question.service.test.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { QuestionService } from '../../src/services/questions/question.service.js';
|
||||
import {
|
||||
createMockDb,
|
||||
selectChainOrdered,
|
||||
selectChainSimple,
|
||||
insertChain,
|
||||
updateChain,
|
||||
} from '../test-utils.js';
|
||||
|
||||
const mockLlmQuestions = [
|
||||
{
|
||||
questionBankId: 'qb-new',
|
||||
type: 'single_choice' as const,
|
||||
questionText: 'New question?',
|
||||
options: [{ key: 'a', text: 'A' }, { key: 'b', text: 'B' }],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'Explanation',
|
||||
stack: 'js' as const,
|
||||
level: 'beginner' as const,
|
||||
},
|
||||
];
|
||||
|
||||
describe('QuestionService', () => {
|
||||
let mockDb: ReturnType<typeof createMockDb>;
|
||||
let mockLlmService: { generateQuestions: ReturnType<typeof vi.fn> };
|
||||
let questionService: QuestionService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockDb = createMockDb();
|
||||
mockLlmService = {
|
||||
generateQuestions: vi.fn().mockResolvedValue({
|
||||
questions: mockLlmQuestions,
|
||||
meta: {
|
||||
llmModel: 'test-model',
|
||||
promptHash: 'hash',
|
||||
generationTimeMs: 100,
|
||||
rawResponse: {},
|
||||
},
|
||||
}),
|
||||
};
|
||||
questionService = new QuestionService(mockDb as never, mockLlmService as never);
|
||||
});
|
||||
|
||||
describe('getQuestionsForTest', () => {
|
||||
it('returns questions from bank when enough approved exist', async () => {
|
||||
const approvedRows = [
|
||||
{
|
||||
id: 'qb-1',
|
||||
type: 'single_choice',
|
||||
questionText: 'Q1?',
|
||||
options: [{ key: 'a', text: 'A' }],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'e',
|
||||
},
|
||||
];
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChainOrdered(approvedRows))
|
||||
.mockReturnValueOnce(selectChainSimple([]));
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(insertChain([]));
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(updateChain([]));
|
||||
|
||||
const result = await questionService.getQuestionsForTest(
|
||||
'user-1',
|
||||
'js',
|
||||
'beginner',
|
||||
1
|
||||
);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].questionBankId).toBe('qb-1');
|
||||
expect(mockLlmService.generateQuestions).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls LLM when not enough questions in bank', async () => {
|
||||
const approvedRows: unknown[] = [];
|
||||
const seenIds: unknown[] = [];
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChainOrdered(approvedRows))
|
||||
.mockReturnValueOnce(selectChainSimple(seenIds));
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(insertChain([{ id: 'qb-new', ...mockLlmQuestions[0] }]))
|
||||
.mockReturnValueOnce(insertChain([]))
|
||||
.mockReturnValueOnce(insertChain([]));
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(updateChain([]));
|
||||
|
||||
const result = await questionService.getQuestionsForTest(
|
||||
'user-1',
|
||||
'js',
|
||||
'beginner',
|
||||
1
|
||||
);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(mockLlmService.generateQuestions).toHaveBeenCalledWith({
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
count: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when not enough questions available', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChainOrdered([]))
|
||||
.mockReturnValueOnce(selectChainSimple([]));
|
||||
mockLlmService.generateQuestions.mockResolvedValueOnce({
|
||||
questions: [],
|
||||
meta: { llmModel: 'x', promptHash: 'y', generationTimeMs: 0, rawResponse: {} },
|
||||
});
|
||||
|
||||
await expect(
|
||||
questionService.getQuestionsForTest('user-1', 'js', 'beginner', 5)
|
||||
).rejects.toMatchObject({ code: 'QUESTIONS_UNAVAILABLE' });
|
||||
});
|
||||
});
|
||||
});
|
||||
230
tests/services/tests.service.test.ts
Normal file
230
tests/services/tests.service.test.ts
Normal file
@@ -0,0 +1,230 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { TestsService } from '../../src/services/tests/tests.service.js';
|
||||
import {
|
||||
createMockDb,
|
||||
selectChain,
|
||||
selectChainOrdered,
|
||||
selectChainWhere,
|
||||
insertChain,
|
||||
updateChain,
|
||||
updateChainReturning,
|
||||
} from '../test-utils.js';
|
||||
|
||||
const mockQuestions = [
|
||||
{
|
||||
questionBankId: 'qb-1',
|
||||
type: 'single_choice' as const,
|
||||
questionText: 'What is 2+2?',
|
||||
options: [{ key: 'a', text: '4' }, { key: 'b', text: '3' }],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'Basic math',
|
||||
},
|
||||
];
|
||||
|
||||
describe('TestsService', () => {
|
||||
let mockDb: ReturnType<typeof createMockDb>;
|
||||
let mockQuestionService: { getQuestionsForTest: ReturnType<typeof vi.fn> };
|
||||
let testsService: TestsService;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockDb = createMockDb();
|
||||
mockQuestionService = {
|
||||
getQuestionsForTest: vi.fn().mockResolvedValue(mockQuestions),
|
||||
};
|
||||
testsService = new TestsService(mockDb as never, mockQuestionService as never);
|
||||
});
|
||||
|
||||
describe('createTest', () => {
|
||||
it('creates a test with questions from QuestionService', async () => {
|
||||
const mockTest = {
|
||||
id: 'test-1',
|
||||
userId: 'user-1',
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
questionCount: 1,
|
||||
mode: 'fixed',
|
||||
status: 'in_progress',
|
||||
score: null,
|
||||
startedAt: new Date(),
|
||||
finishedAt: null,
|
||||
timeLimitSeconds: null,
|
||||
};
|
||||
const mockTqRows = [
|
||||
{
|
||||
id: 'tq-1',
|
||||
testId: 'test-1',
|
||||
questionBankId: 'qb-1',
|
||||
orderNumber: 1,
|
||||
type: 'single_choice',
|
||||
questionText: 'What is 2+2?',
|
||||
options: [{ key: 'a', text: '4' }],
|
||||
correctAnswer: 'a',
|
||||
explanation: 'Basic math',
|
||||
userAnswer: null,
|
||||
isCorrect: null,
|
||||
answeredAt: null,
|
||||
},
|
||||
];
|
||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(insertChain([mockTest]))
|
||||
.mockReturnValueOnce(insertChain([]));
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChainOrdered(mockTqRows)
|
||||
);
|
||||
|
||||
const result = await testsService.createTest('user-1', {
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
questionCount: 1,
|
||||
});
|
||||
|
||||
expect(result.id).toBe('test-1');
|
||||
expect(result.questions).toHaveLength(1);
|
||||
expect(mockQuestionService.getQuestionsForTest).toHaveBeenCalledWith(
|
||||
'user-1',
|
||||
'js',
|
||||
'beginner',
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
it('throws when questionCount is out of range', async () => {
|
||||
await expect(
|
||||
testsService.createTest('user-1', {
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
questionCount: 0,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
|
||||
|
||||
await expect(
|
||||
testsService.createTest('user-1', {
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
questionCount: 51,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('answerQuestion', () => {
|
||||
it('returns updated question snapshot when answer is correct', async () => {
|
||||
const mockTest = { id: 't-1', userId: 'user-1', status: 'in_progress' };
|
||||
const mockTq = {
|
||||
id: 'tq-1',
|
||||
testId: 't-1',
|
||||
correctAnswer: 'a',
|
||||
userAnswer: null,
|
||||
questionBankId: 'qb-1',
|
||||
orderNumber: 1,
|
||||
type: 'single_choice',
|
||||
questionText: 'Q?',
|
||||
options: [{ key: 'a', text: 'A' }],
|
||||
explanation: 'exp',
|
||||
};
|
||||
const updatedTq = { ...mockTq, userAnswer: 'a', isCorrect: true, answeredAt: new Date() };
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([mockTest]))
|
||||
.mockReturnValueOnce(selectChain([mockTq]));
|
||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
updateChainReturning([updatedTq])
|
||||
);
|
||||
|
||||
const result = await testsService.answerQuestion('user-1', 't-1', 'tq-1', 'a');
|
||||
|
||||
expect(result.isCorrect).toBe(true);
|
||||
expect(result.userAnswer).toBe('a');
|
||||
});
|
||||
|
||||
it('throws when test not found', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(selectChain([]));
|
||||
|
||||
await expect(
|
||||
testsService.answerQuestion('user-1', 'bad-id', 'tq-1', 'a')
|
||||
).rejects.toMatchObject({ code: 'NOT_FOUND' });
|
||||
});
|
||||
|
||||
it('throws when test is already finished', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
||||
selectChain([{ id: 't-1', userId: 'user-1', status: 'completed' }])
|
||||
);
|
||||
|
||||
await expect(
|
||||
testsService.answerQuestion('user-1', 't-1', 'tq-1', 'a')
|
||||
).rejects.toMatchObject({ code: 'TEST_ALREADY_FINISHED' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('finishTest', () => {
|
||||
it('throws when there are unanswered questions', async () => {
|
||||
const mockTest = { id: 't-1', userId: 'user-1', status: 'in_progress', stack: 'js', level: 'beginner' };
|
||||
const mockQuestionsWithUnanswered = [
|
||||
{ id: 'tq-1', testId: 't-1', userAnswer: 'a', isCorrect: true },
|
||||
{ id: 'tq-2', testId: 't-1', userAnswer: null, isCorrect: null },
|
||||
];
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([mockTest]))
|
||||
.mockReturnValueOnce(selectChainWhere(mockQuestionsWithUnanswered));
|
||||
|
||||
await expect(
|
||||
testsService.finishTest('user-1', 't-1')
|
||||
).rejects.toMatchObject({ code: 'NO_ANSWERS' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getById', () => {
|
||||
it('returns null when test not found', async () => {
|
||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(selectChain([]));
|
||||
|
||||
const result = await testsService.getById('user-1', 'bad-id');
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it('returns test with questions when found', async () => {
|
||||
const mockTest = {
|
||||
id: 't-1',
|
||||
userId: 'user-1',
|
||||
stack: 'js',
|
||||
level: 'beginner',
|
||||
questionCount: 2,
|
||||
mode: 'fixed',
|
||||
status: 'in_progress',
|
||||
score: null,
|
||||
startedAt: new Date(),
|
||||
finishedAt: null,
|
||||
timeLimitSeconds: null,
|
||||
};
|
||||
const mockTqRows = [
|
||||
{ id: 'tq-1', testId: 't-1', orderNumber: 1, questionBankId: 'qb-1', type: 'single_choice', questionText: 'Q1', options: [], correctAnswer: 'a', explanation: 'e', userAnswer: null, isCorrect: null, answeredAt: null },
|
||||
];
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChain([mockTest]))
|
||||
.mockReturnValueOnce(selectChainOrdered(mockTqRows));
|
||||
|
||||
const result = await testsService.getById('user-1', 't-1');
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.id).toBe('t-1');
|
||||
expect(result!.questions).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getHistory', () => {
|
||||
it('returns paginated test history', async () => {
|
||||
const mockTests = [
|
||||
{ id: 't-1', userId: 'user-1', stack: 'js', level: 'beginner', questionCount: 1, mode: 'fixed', status: 'completed', score: 100, startedAt: new Date(), finishedAt: new Date(), timeLimitSeconds: null },
|
||||
];
|
||||
const mockTqRows = [];
|
||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
||||
.mockReturnValueOnce(selectChainOrdered(mockTests))
|
||||
.mockReturnValueOnce(selectChainOrdered(mockTqRows));
|
||||
|
||||
const result = await testsService.getHistory('user-1', { limit: 10, offset: 0 });
|
||||
|
||||
expect(result.tests).toHaveLength(1);
|
||||
expect(result.total).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
11
tests/setup.ts
Normal file
11
tests/setup.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { beforeAll, vi } from 'vitest';
|
||||
|
||||
beforeAll(() => {
|
||||
vi.stubEnv('NODE_ENV', 'test');
|
||||
if (!process.env.DATABASE_URL) {
|
||||
process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/test';
|
||||
}
|
||||
if (!process.env.JWT_SECRET) {
|
||||
process.env.JWT_SECRET = 'test-secret-min-32-chars-long-for-validation';
|
||||
}
|
||||
});
|
||||
12
tests/smoke.test.ts
Normal file
12
tests/smoke.test.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createMockDb } from './test-utils.js';
|
||||
|
||||
describe('test-utils', () => {
|
||||
it('createMockDb returns mock with select, insert, update, delete', () => {
|
||||
const db = createMockDb();
|
||||
expect(db.select).toBeDefined();
|
||||
expect(db.insert).toBeDefined();
|
||||
expect(db.update).toBeDefined();
|
||||
expect(db.delete).toBeDefined();
|
||||
});
|
||||
});
|
||||
165
tests/test-utils.ts
Normal file
165
tests/test-utils.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { vi } from 'vitest';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
||||
import type * as schema from '../src/db/schema/index.js';
|
||||
|
||||
export type MockDb = {
|
||||
select: ReturnType<NodePgDatabase<typeof schema>['select']>;
|
||||
insert: ReturnType<NodePgDatabase<typeof schema>['insert']>;
|
||||
update: ReturnType<NodePgDatabase<typeof schema>['update']>;
|
||||
delete: ReturnType<NodePgDatabase<typeof schema>['delete']>;
|
||||
};
|
||||
|
||||
/** Build a select chain that resolves to the given rows at .limit(n) */
|
||||
export function selectChain(resolveAtLimit: unknown[] = []) {
|
||||
const limitFn = vi.fn().mockResolvedValue(resolveAtLimit);
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
where: vi.fn().mockReturnValue({
|
||||
limit: limitFn,
|
||||
orderBy: vi.fn().mockReturnValue({ limit: limitFn }),
|
||||
}),
|
||||
limit: limitFn,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a select chain for .from().where().orderBy() - orderBy is terminal */
|
||||
export function selectChainOrdered(resolveAtOrderBy: unknown[] = []) {
|
||||
const orderByThenable = {
|
||||
then: (resolve: (v: unknown) => void) => resolve(resolveAtOrderBy),
|
||||
};
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
where: vi.fn().mockReturnValue({
|
||||
orderBy: vi.fn().mockReturnValue(orderByThenable),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a select chain for .from().where() with no orderBy - used by select({...}).from() */
|
||||
export function selectChainSimple(resolveRows: unknown[] = []) {
|
||||
const thenable = { then: (resolve: (v: unknown) => void) => resolve(resolveRows) };
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
where: vi.fn().mockReturnValue(thenable),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a select chain for .from().where() - where is terminal (no orderBy/limit) */
|
||||
export function selectChainWhere(resolveAtWhere: unknown[] = []) {
|
||||
const thenable = { then: (resolve: (v: unknown) => void) => resolve(resolveAtWhere) };
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
where: vi.fn().mockReturnValue(thenable),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a select chain for .from().where().orderBy().limit().offset() */
|
||||
export function selectChainOrderedLimitOffset(resolveRows: unknown[] = []) {
|
||||
const offsetFn = vi.fn().mockResolvedValue(resolveRows);
|
||||
return {
|
||||
from: vi.fn().mockReturnValue({
|
||||
where: vi.fn().mockReturnValue({
|
||||
orderBy: vi.fn().mockReturnValue({
|
||||
limit: vi.fn().mockReturnValue({
|
||||
offset: offsetFn,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an insert chain that resolves at .returning() or .values() */
|
||||
export function insertChain(resolveAtReturning: unknown[] = []) {
|
||||
const returningFn = vi.fn().mockResolvedValue(resolveAtReturning);
|
||||
const chainFromValues = {
|
||||
returning: returningFn,
|
||||
then: (resolve: (v?: unknown) => void) => resolve(undefined),
|
||||
};
|
||||
return {
|
||||
values: vi.fn().mockReturnValue(chainFromValues),
|
||||
returning: returningFn,
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an update chain that resolves at .where() */
|
||||
export function updateChain(resolveAtWhere: unknown[] = []) {
|
||||
return {
|
||||
set: vi.fn().mockReturnValue({
|
||||
where: vi.fn().mockResolvedValue(resolveAtWhere),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an update chain with .where().returning() */
|
||||
export function updateChainReturning(resolveAtReturning: unknown[] = []) {
|
||||
const returningFn = vi.fn().mockResolvedValue(resolveAtReturning);
|
||||
return {
|
||||
set: vi.fn().mockReturnValue({
|
||||
where: vi.fn().mockReturnValue({
|
||||
returning: returningFn,
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build a delete chain that resolves at .where() */
|
||||
export function deleteChain() {
|
||||
return {
|
||||
where: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a chainable mock for Drizzle DB operations.
|
||||
* Use mockReturnValue with selectChain/insertChain/updateChain/deleteChain.
|
||||
*/
|
||||
export function createMockDb(): MockDb {
|
||||
const chain = {
|
||||
from: vi.fn().mockReturnThis(),
|
||||
where: vi.fn().mockReturnThis(),
|
||||
values: vi.fn().mockReturnThis(),
|
||||
set: vi.fn().mockReturnThis(),
|
||||
orderBy: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
returning: vi.fn().mockReturnThis(),
|
||||
};
|
||||
|
||||
return {
|
||||
select: vi.fn().mockReturnValue(chain),
|
||||
insert: vi.fn().mockReturnValue(chain),
|
||||
update: vi.fn().mockReturnValue(chain),
|
||||
delete: vi.fn().mockReturnValue(chain),
|
||||
} as unknown as MockDb;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a minimal mock Fastify app with db for route/integration tests.
|
||||
* Use buildApp() from app.ts for full integration tests.
|
||||
*/
|
||||
export function createMockApp(): FastifyInstance & { db: MockDb } {
|
||||
return {
|
||||
db: createMockDb(),
|
||||
log: {
|
||||
child: () => ({
|
||||
debug: () => {},
|
||||
info: () => {},
|
||||
warn: () => {},
|
||||
error: () => {},
|
||||
trace: () => {},
|
||||
fatal: () => {},
|
||||
}),
|
||||
debug: () => {},
|
||||
info: () => {},
|
||||
warn: () => {},
|
||||
error: () => {},
|
||||
trace: () => {},
|
||||
fatal: () => {},
|
||||
},
|
||||
} as FastifyInstance & { db: MockDb };
|
||||
}
|
||||
40
vitest.config.ts
Normal file
40
vitest.config.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import { resolve } from 'path';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['tests/**/*.test.ts', 'tests/**/*.spec.ts'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
reporter: ['text', 'json', 'lcov'],
|
||||
include: [
|
||||
'src/services/auth/**/*.ts',
|
||||
'src/services/llm/**/*.ts',
|
||||
'src/services/questions/**/*.ts',
|
||||
'src/services/tests/**/*.ts',
|
||||
'src/services/admin/**/*.ts',
|
||||
],
|
||||
exclude: [
|
||||
'src/services/**/*.d.ts',
|
||||
'**/*.test.ts',
|
||||
'**/*.spec.ts',
|
||||
'**/index.ts',
|
||||
],
|
||||
thresholds: {
|
||||
lines: 70,
|
||||
functions: 70,
|
||||
branches: 68,
|
||||
statements: 70,
|
||||
},
|
||||
},
|
||||
setupFiles: ['tests/setup.ts'],
|
||||
testTimeout: 10000,
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, 'src'),
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user