Files
povtornyy-ekzamen-2-sravnit…/tests/compare.test.js
T

74 lines
2.2 KiB
JavaScript

/**
* Unit tests for the compare function.
*
* These tests mock the Tavily API calls to ensure that the compare
* function behaves correctly without making real HTTP requests.
*/
import { compare } from '../src/index.js';
import fetch from 'node-fetch';
jest.mock('node-fetch', () => jest.fn());
const { Response } = jest.requireActual('node-fetch');
describe('compare', () => {
beforeEach(() => {
fetch.mockClear();
});
test('returns results for three entities', async () => {
const mockResponses = [
{ result: 'entity1 result' },
{ result: 'entity2 result' },
{ result: 'entity3 result' }
];
fetch
.mockResolvedValueOnce(new Response(JSON.stringify(mockResponses[0]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify(mockResponses[1]), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify(mockResponses[2]), { status: 200 }));
const result = await compare('entity1', 'entity2', 'entity3');
expect(result).toEqual({
entity1: mockResponses[0],
entity2: mockResponses[1],
entity3: mockResponses[2]
});
expect(fetch).toHaveBeenCalledTimes(3);
expect(fetch).toHaveBeenNthCalledWith(
1,
expect.stringContaining('entity1'),
expect.any(Object)
);
expect(fetch).toHaveBeenNthCalledWith(
2,
expect.stringContaining('entity2'),
expect.any(Object)
);
expect(fetch).toHaveBeenNthCalledWith(
3,
expect.stringContaining('entity3'),
expect.any(Object)
);
});
test('throws error if any API call fails', async () => {
fetch
.mockResolvedValueOnce(new Response(JSON.stringify({ result: 'ok' }), { status: 200 }))
.mockResolvedValueOnce(new Response('Not Found', { status: 404 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ result: 'ok' }), { status: 200 }));
await expect(compare('entity1', 'entity2', 'entity3')).rejects.toThrow(
/Comparison failed/
);
});
test('throws error if missing entity arguments', async () => {
await expect(compare('entity1', 'entity2')).rejects.toThrow(
/All three entities must be provided/
);
});
});