Files
unai/tests/chatbot.test.ts
T
2025-07-14 10:14:20 +04:00

102 lines
2.7 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UTASChatBot, { UserContext } from '../src/lib/chatbot';
// Mock environment variables
vi.mock('process', () => ({
env: {
OPENROUTER_API_KEY: 'test-key',
OLLAMA_URL: 'http://localhost:11434',
MODEL_COMMAND_R7B: 'command-r7b-arabic'
}
}));
// Mock OpenAI client
vi.mock('openai', () => {
return {
OpenAI: vi.fn().mockImplementation(() => ({
chat: {
completions: {
create: vi.fn().mockResolvedValue({
choices: [
{
message: {
content: 'This is a mocked AI response'
}
}
]
})
}
}
}))
};
});
// Mock Ollama client
vi.mock('ollama', () => {
return {
Ollama: vi.fn().mockImplementation(() => ({
chat: vi.fn().mockResolvedValue({
message: {
content: 'This is a mocked Ollama response'
}
})
}))
};
});
describe('UTASChatBot', () => {
let chatbot: UTASChatBot;
beforeEach(() => {
chatbot = new UTASChatBot('test-api-key');
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should detect Arabic language correctly', () => {
expect(chatbot.detectLanguage('Hello')).toBe('en');
expect(chatbot.detectLanguage('مرحبا')).toBe('ar');
});
it('should generate responses for anonymous users with public info only', async () => {
const response = await chatbot.generateResponse('Tell me about scholarships');
// We would expect the response not to contain any personalized information
expect(response).not.toContain('Your application status');
expect(response).not.toContain('Your account balance');
});
it('should generate personalized responses for authenticated users', async () => {
const userContext: UserContext = {
role: 'student',
token: 'test-token',
profile: {
name: 'John Doe',
email: 'john@example.com',
year: 2,
faculty: 'Engineering',
balance: 1500
}
};
const response = await chatbot.generateResponse('Tell me about my account', userContext);
// The implementation should pass userContext to the AI service
// For now, we're just testing the function doesn't crash
expect(response).toBeTruthy();
});
it('should fall back to Ollama when OpenRouter API key is not available', async () => {
// Create a new instance with empty API key
const noKeyBot = new UTASChatBot('');
const response = await noKeyBot.generateResponse('Hello');
// Since we're mocking, we just verify it doesn't crash
expect(response).toBeTruthy();
});
});