ai-embedapi
Version:
A powerful JavaScript SDK to interact with multiple AI models (OpenAI, Anthropic, VertexAI, XAI) for text generation and other AI capabilities using the EmbedAPI service.
76 lines (63 loc) • 2.35 kB
JavaScript
const OneAIAPI = require('../src/OneAIAPI');
// Mock fetch
global.fetch = jest.fn();
describe('OneAIAPI', () => {
let api;
const mockApiKey = 'test-api-key';
beforeEach(() => {
api = new OneAIAPI(mockApiKey);
fetch.mockClear();
});
describe('constructor', () => {
test('should throw error if no API key provided', () => {
expect(() => new OneAIAPI()).toThrow('API key is required');
});
test('should initialize with API key', () => {
expect(api.apiKey).toBe(mockApiKey);
});
});
describe('generateText', () => {
const mockOptions = {
service: 'chat',
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: 'Hello' }]
};
test('should make correct API call', async () => {
const mockResponse = {
ok: true,
json: () => Promise.resolve({ choices: [{ message: { content: 'Hello!' } }] })
};
fetch.mockResolvedValueOnce(mockResponse);
await api.generateText(mockOptions);
expect(fetch).toHaveBeenCalledWith(
expect.stringContaining('/generate'),
expect.objectContaining({
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': mockApiKey
},
body: JSON.stringify(mockOptions)
})
);
});
test('should handle API errors', async () => {
const errorMessage = 'API Error';
const mockResponse = {
ok: false,
json: () => Promise.resolve({ error: errorMessage, code: 400 })
};
fetch.mockResolvedValueOnce(mockResponse);
await expect(api.generateText(mockOptions))
.rejects
.toThrow(`API Error: ${errorMessage}`);
});
test('should handle network errors', async () => {
const networkError = new Error('Network error');
fetch.mockRejectedValueOnce(networkError);
await expect(api.generateText(mockOptions))
.rejects
.toThrow('Network error');
});
});
});