Skip to content

Commit

Permalink
test: added tests for export API calls
Browse files Browse the repository at this point in the history
  • Loading branch information
thorsten committed Jan 24, 2025
1 parent c566ad3 commit d8d2936
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions phpmyfaq/admin/assets/src/api/export.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { describe, it, expect, vi } from 'vitest';
import { createReport } from './export';

describe('createReport', () => {
it('should create a report and return a Blob if successful', async () => {
const mockBlob = new Blob(['Report data'], { type: 'application/pdf' });
global.fetch = vi.fn(() =>
Promise.resolve({
ok: true,
blob: () => Promise.resolve(mockBlob),
} as Response)
);

const data = { key: 'value' };
const csrfToken = 'csrfToken';
const result = await createReport(data, csrfToken);

expect(result).toBe(mockBlob);
expect(global.fetch).toHaveBeenCalledWith('./api/export/report', {
method: 'POST',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: data,
csrfToken: csrfToken,
}),
redirect: 'follow',
referrerPolicy: 'no-referrer',
});
});

it('should return JSON response if the network response is not ok', async () => {
const mockResponse = { success: false, message: 'Error' };
global.fetch = vi.fn(() =>
Promise.resolve({
ok: false,
json: () => Promise.resolve(mockResponse),
} as Response)
);

const data = { key: 'value' };
const csrfToken = 'csrfToken';
const result = await createReport(data, csrfToken);

expect(result).toEqual(mockResponse);
});

it('should log an error if fetch fails', async () => {
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const mockError = new Error('Fetch failed');
global.fetch = vi.fn(() => Promise.reject(mockError));

const data = { key: 'value' };
const csrfToken = 'csrfToken';

await createReport(data, csrfToken);

expect(consoleErrorSpy).toHaveBeenCalledWith(mockError);
consoleErrorSpy.mockRestore();
});
});

0 comments on commit d8d2936

Please sign in to comment.