Files
GandClaude Opus 5 9cf91812aa refactor(test): jest -> vitest (#165)
Jest is CJS-rooted, needs transform configuration for ESM and TypeScript, and
every shared CI template has to accommodate its dialect. vitest is ESM/TS
native and jest-compatible at the API level.

`globals: true` keeps describe/it/expect/beforeEach/vi available without
imports, so the diff is the jest.* API names and nothing else. Only TYPES had
to be imported, because a type cannot come from a global.

next/jest supplied the path alias, the next/server mock and the jsdom
environment implicitly; vitest.config.ts states them, so they are visible
rather than inherited. The transformIgnorePatterns override for ESM-only
packages (ai-kit) is DELETED rather than translated — jest ran CJS and died on
`Unexpected token export`, which is the entire reason that workaround existed.
vitest loads ESM natively.

Three things only running the suite could have found:

  * __mocks__/next/server.ts was outside the first rewrite pass, so every test
    importing it died with `jest is not defined`.
  * vitest builds a mocked constructor with Reflect.construct, and an ARROW
    function is not constructible — `vi.fn().mockImplementation(() => ({...}))`
    threw "is not a constructor" the moment the code did `new SESClient()`.
    jest tolerated it. Two mocks needed function expressions.
  * removing @types/jest took the global describe/it/expect declarations with
    it; tsconfig now carries "types": ["vitest/globals"].

Verified locally before pushing: 272 passed, 2 skipped, 23 files.


Claude-Session: https://claude.ai/code/session_01UvjGNAS9CMfEGNW26tUR4P

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 09:15:12 +00:00

174 lines
5.3 KiB
TypeScript

import { saveUserContext, getRelevantContext, type UserContextEntry } from '@/lib/context/store';
// Mock dependencies
vi.mock('@/lib/supabase', () => ({
getServiceClient: vi.fn(),
}));
vi.mock('@/lib/embeddings', () => ({
generateEmbedding: vi.fn(),
}));
import { getServiceClient } from '@/lib/supabase';
import { generateEmbedding } from '@/lib/embeddings';
import type { Mock } from 'vitest';
const mockInsert = vi.fn();
const mockRpc = vi.fn();
const mockSupabase = {
from: vi.fn(() => ({ insert: mockInsert })),
rpc: mockRpc,
};
beforeEach(() => {
vi.clearAllMocks();
(getServiceClient as Mock).mockReturnValue(mockSupabase);
(generateEmbedding as Mock).mockResolvedValue([0.1, 0.2, 0.3]);
});
describe('saveUserContext', () => {
it('returns 0 for empty facts array', async () => {
const result = await saveUserContext('user-1', []);
expect(result).toBe(0);
expect(getServiceClient).not.toHaveBeenCalled();
});
it('saves facts with generated embeddings', async () => {
mockInsert.mockResolvedValue({ error: null });
const facts = [
{
content: 'User lives in Zürich',
domains: ['general'],
sourceType: 'conversation' as const,
},
{
content: 'User has a cat',
domains: ['general'],
sourceType: 'conversation' as const,
sourceId: 'conv-1',
},
];
const result = await saveUserContext('user-1', facts);
expect(result).toBe(2);
expect(generateEmbedding).toHaveBeenCalledTimes(2);
expect(generateEmbedding).toHaveBeenCalledWith('User lives in Zürich');
expect(generateEmbedding).toHaveBeenCalledWith('User has a cat');
expect(mockInsert).toHaveBeenCalledTimes(2);
expect(mockInsert).toHaveBeenCalledWith(
expect.objectContaining({
user_id: 'user-1',
content: 'User lives in Zürich',
domains: ['general'],
source_type: 'conversation',
embedding: [0.1, 0.2, 0.3],
confidence: 0.8, // default
}),
);
});
it('uses provided confidence instead of default', async () => {
mockInsert.mockResolvedValue({ error: null });
await saveUserContext('user-1', [
{ content: 'Fact', domains: ['legal'], sourceType: 'document' as const, confidence: 0.95 },
]);
expect(mockInsert).toHaveBeenCalledWith(expect.objectContaining({ confidence: 0.95 }));
});
it('skips facts that fail to save', async () => {
mockInsert
.mockResolvedValueOnce({ error: { message: 'duplicate' } })
.mockResolvedValueOnce({ error: null });
const facts = [
{ content: 'Fact 1', domains: ['general'], sourceType: 'conversation' as const },
{ content: 'Fact 2', domains: ['general'], sourceType: 'conversation' as const },
];
const result = await saveUserContext('user-1', facts);
expect(result).toBe(1); // only second succeeded
});
it('skips facts where embedding generation throws', async () => {
(generateEmbedding as Mock)
.mockRejectedValueOnce(new Error('model load failed'))
.mockResolvedValueOnce([0.1, 0.2]);
mockInsert.mockResolvedValue({ error: null });
const facts = [
{ content: 'Fact 1', domains: ['general'], sourceType: 'conversation' as const },
{ content: 'Fact 2', domains: ['general'], sourceType: 'conversation' as const },
];
const result = await saveUserContext('user-1', facts);
expect(result).toBe(1);
});
});
describe('getRelevantContext', () => {
it('calls RPC with correct parameters', async () => {
const mockEntries: UserContextEntry[] = [
{
id: '1',
content: 'User is 30',
domains: ['general'],
source_type: 'conversation',
confidence: 0.9,
similarity: 0.8,
},
];
mockRpc.mockResolvedValue({ data: mockEntries, error: null });
const result = await getRelevantContext('user-1', ['legal', 'general'], 'age question');
expect(generateEmbedding).toHaveBeenCalledWith('age question');
expect(mockRpc).toHaveBeenCalledWith('get_relevant_context', {
p_user_id: 'user-1',
p_domains: ['legal', 'general'],
p_embedding: [0.1, 0.2, 0.3],
p_match_threshold: 0.3,
p_max_results: 10,
});
expect(result).toEqual(mockEntries);
});
it('uses custom maxResults and matchThreshold', async () => {
mockRpc.mockResolvedValue({ data: [], error: null });
await getRelevantContext('user-1', ['health'], 'query', 5, 0.5);
expect(mockRpc).toHaveBeenCalledWith(
'get_relevant_context',
expect.objectContaining({
p_max_results: 5,
p_match_threshold: 0.5,
}),
);
});
it('returns empty array on RPC error', async () => {
mockRpc.mockResolvedValue({ data: null, error: { message: 'RPC failed' } });
const result = await getRelevantContext('user-1', ['general'], 'test');
expect(result).toEqual([]);
});
it('returns empty array when embedding generation fails', async () => {
(generateEmbedding as Mock).mockRejectedValue(new Error('model error'));
const result = await getRelevantContext('user-1', ['general'], 'test');
expect(result).toEqual([]);
});
it('returns empty array when data is null', async () => {
mockRpc.mockResolvedValue({ data: null, error: null });
const result = await getRelevantContext('user-1', ['general'], 'test');
expect(result).toEqual([]);
});
});