/[sudobot]/branches/8.x/tests/utils/download.test.ts
ViewVC logotype

Annotation of /branches/8.x/tests/utils/download.test.ts

Parent Directory Parent Directory | Revision Log Revision Log


Revision 577 - (hide annotations)
Mon Jul 29 18:52:37 2024 UTC (8 months ago) by rakinar2
File MIME type: application/typescript
File size: 2289 byte(s)
chore: add old version archive branches (2.x to 9.x-dev)
1 rakinar2 577 import { join } from "path";
2     import stream from "stream";
3     import { afterEach, describe, expect, it, vi } from "vitest";
4     import { downloadFile } from "../../src/utils/download";
5    
6     const axiosMocks = vi.hoisted(() => {
7     return {
8     request: vi.fn(() => {
9     return {
10     status: 200,
11     data: {
12     pipe: vi.fn()
13     }
14     };
15     })
16     };
17     });
18    
19     vi.mock("fs", () => {
20     return {
21     createWriteStream: vi.fn(() => {
22     return {
23     write: vi.fn(),
24     close: vi.fn(callback => callback(null)),
25     closed: false
26     };
27     })
28     };
29     });
30    
31     vi.mock("stream", () => {
32     return {
33     default: {
34     finished: vi.fn((stream, callback) => callback(null))
35     }
36     };
37     });
38    
39     vi.mock("axios", () => {
40     return {
41     default: {
42     request: axiosMocks.request
43     }
44     };
45     });
46    
47     describe("downloadFile", () => {
48     afterEach(() => {
49     vi.resetAllMocks();
50     });
51    
52     it("should download a file", async () => {
53     const url = "https://example.com/file.txt";
54     const destinationDirectory = "path/to/dir";
55     const name = "file.txt";
56     const axiosOptions = { headers: { Authorization: "Bearer token" } };
57    
58     const result = await downloadFile({ url, path: destinationDirectory, name, axiosOptions });
59    
60     expect(result).toEqual({
61     filePath: join(destinationDirectory, name),
62     storagePath: destinationDirectory
63     });
64    
65     expect(stream.finished).toHaveBeenCalledTimes(1);
66     });
67    
68     it("should throw an error if the request fails", async () => {
69     const url = "https://example.com/file.txt";
70     const destinationDirectory = "path/to/dir";
71     const name = "file.txt";
72     const axiosOptions = { headers: { Authorization: "Bearer token" } };
73    
74     axiosMocks.request.mockReturnValue({
75     status: 500,
76     data: {
77     pipe: vi.fn()
78     }
79     });
80    
81     expect(
82     downloadFile({ url, path: destinationDirectory, name, axiosOptions })
83     ).rejects.toThrow("HTTP error: Non 2xx response received: code 500");
84     expect(stream.finished).toHaveBeenCalledTimes(0);
85     });
86     });

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26