|
| 1 | +import { describe, it, expect, vi, afterEach } from 'vitest'; |
| 2 | +import { fetchOpenSearchAction, fetchOpenSearchStatistics } from './opensearch'; |
| 3 | + |
| 4 | +describe('OpenSearch API', () => { |
| 5 | + afterEach(() => { |
| 6 | + vi.restoreAllMocks(); |
| 7 | + }); |
| 8 | + |
| 9 | + describe('fetchOpenSearchAction', () => { |
| 10 | + it('should fetch OpenSearch action and return JSON response if successful', async () => { |
| 11 | + const mockResponse = { success: true, message: 'Action executed' }; |
| 12 | + global.fetch = vi.fn(() => |
| 13 | + Promise.resolve({ |
| 14 | + ok: true, |
| 15 | + json: () => Promise.resolve(mockResponse), |
| 16 | + } as Response) |
| 17 | + ); |
| 18 | + |
| 19 | + const action = 'index'; |
| 20 | + const result = await fetchOpenSearchAction(action); |
| 21 | + |
| 22 | + expect(result).toEqual(mockResponse); |
| 23 | + expect(global.fetch).toHaveBeenCalledWith('./api/opensearch/index', { |
| 24 | + method: 'GET', |
| 25 | + cache: 'no-cache', |
| 26 | + headers: { |
| 27 | + 'Content-Type': 'application/json', |
| 28 | + }, |
| 29 | + redirect: 'follow', |
| 30 | + referrerPolicy: 'no-referrer', |
| 31 | + }); |
| 32 | + }); |
| 33 | + |
| 34 | + it('should throw an error if fetch fails', async () => { |
| 35 | + const mockError = new Error('Fetch failed'); |
| 36 | + global.fetch = vi.fn(() => Promise.reject(mockError)); |
| 37 | + |
| 38 | + await expect(fetchOpenSearchAction('index')).rejects.toThrow(mockError); |
| 39 | + }); |
| 40 | + }); |
| 41 | + |
| 42 | + describe('fetchOpenSearchStatistics', () => { |
| 43 | + it('should fetch OpenSearch statistics and return JSON response if successful', async () => { |
| 44 | + const mockResponse = { |
| 45 | + status: 'green', |
| 46 | + documents: 123, |
| 47 | + indices: 5, |
| 48 | + size: '10GB', |
| 49 | + }; |
| 50 | + |
| 51 | + global.fetch = vi.fn(() => |
| 52 | + Promise.resolve({ |
| 53 | + ok: true, |
| 54 | + json: () => Promise.resolve(mockResponse), |
| 55 | + } as Response) |
| 56 | + ); |
| 57 | + |
| 58 | + const result = await fetchOpenSearchStatistics(); |
| 59 | + |
| 60 | + expect(result).toEqual(mockResponse); |
| 61 | + expect(global.fetch).toHaveBeenCalledWith('./api/opensearch/statistics', { |
| 62 | + method: 'GET', |
| 63 | + cache: 'no-cache', |
| 64 | + headers: { |
| 65 | + 'Content-Type': 'application/json', |
| 66 | + }, |
| 67 | + redirect: 'follow', |
| 68 | + referrerPolicy: 'no-referrer', |
| 69 | + }); |
| 70 | + }); |
| 71 | + |
| 72 | + it('should throw an error if fetch fails', async () => { |
| 73 | + const mockError = new Error('Fetch failed'); |
| 74 | + global.fetch = vi.fn(() => Promise.reject(mockError)); |
| 75 | + |
| 76 | + await expect(fetchOpenSearchStatistics()).rejects.toThrow(mockError); |
| 77 | + }); |
| 78 | + }); |
| 79 | +}); |
0 commit comments