const nock = require('nock'); const { compareEntities } = require('../src/compare'); require('dotenv').config({ path: '.env.example' }); describe('compareEntities', () => { const baseUrl = 'https://api.tavily.com'; const apiKey = 'test-key'; beforeAll(() => { process.env.TAVILY_API_KEY = apiKey; }); afterEach(() => { nock.cleanAll(); }); test('returns ranked results based on number of results', async () => { nock(baseUrl) .post('/search', { query: 'entity1' }) .reply(200, { results: [{}, {}] }); // 2 results nock(baseUrl) .post('/search', { query: 'entity2' }) .reply(200, { results: [{}, {}, {}] }); // 3 results nock(baseUrl) .post('/search', { query: 'entity3' }) .reply(200, { results: [{}, {}] }); // 2 results const result = await compareEntities('entity1', 'entity2', 'entity3'); expect(result.ranked[0].entity).toBe('entity2'); expect(result.ranked[1].entity).toBe('entity1'); expect(result.ranked[2].entity).toBe('entity3'); }); test('throws error on empty entity', async () => { await expect(compareEntities('', 'b', 'c')).rejects.toThrow( 'All entities must be non-empty strings.' ); }); test('handles API error', async () => { nock(baseUrl) .post('/search', { query: 'entity1' }) .reply(401, { error: 'Invalid API key' }); nock(baseUrl) .post('/search', { query: 'entity2' }) .reply(200, { results: [] }); nock(baseUrl) .post('/search', { query: 'entity3' }) .reply(200, { results: [] }); await expect(compareEntities('entity1', 'entity2', 'entity3')).rejects.toThrow( 'Tavily API error: 401 Invalid API key' ); }); test('handles network failure', async () => { nock(baseUrl) .post('/search', { query: 'entity1' }) .replyWithError('Network down'); nock(baseUrl) .post('/search', { query: 'entity2' }) .reply(200, { results: [] }); nock(baseUrl) .post('/search', { query: 'entity3' }) .reply(200, { results: [] }); await expect(compareEntities('entity1', 'entity2', 'entity3')).rejects.toThrow( 'Network error: Network down' ); }); });