-
-
Notifications
You must be signed in to change notification settings - Fork 256
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test: added tests for export API calls
- Loading branch information
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
}); |