Skip to content

Commit 633d6a7

Browse files
committed
added browser util tests
1 parent 01bc144 commit 633d6a7

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

src/utils/browser.spec.ts

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* Copyright (c) 2024 The Diffusion Studio Authors
3+
*
4+
* This Source Code Form is subject to the terms of the Mozilla
5+
* Public License, v. 2.0 that can be found in the LICENSE file.
6+
*/
7+
8+
import { beforeEach, describe, expect, it, vi } from 'vitest';
9+
import { downloadObject, showFileDialog } from './browser';
10+
11+
describe('The browser utils', () => {
12+
const a = document.createElement('a');
13+
const input = document.createElement('input');
14+
15+
const clickSpy = vi.spyOn(a, 'click');
16+
const removeSpy = vi.spyOn(a, 'remove');
17+
const createSpy = vi.spyOn(document, 'createElement').mockImplementation((tag: string) => {
18+
expect(tag).toBeTypeOf('string');
19+
20+
if (tag == 'a') {
21+
return a;
22+
} else {
23+
return input;
24+
}
25+
});
26+
27+
beforeEach(() => {
28+
clickSpy.mockClear();
29+
removeSpy.mockClear();
30+
createSpy.mockClear();
31+
})
32+
33+
it('should download an object from an url (downloadObject)', async () => {
34+
downloadObject('https://myurl.com/example.mp4');
35+
expect(a.download).toBe('untitled');
36+
expect(a.href).toBe('https://myurl.com/example.mp4');
37+
38+
expect(createSpy).toBeCalledTimes(1);
39+
expect(clickSpy).toBeCalledTimes(1);
40+
expect(removeSpy).toBeCalledTimes(1);
41+
});
42+
43+
it('should download an a blob with custom name (downloadObject)', async () => {
44+
downloadObject(new Blob(), 'temp.mp4');
45+
expect(a.download).toBe('temp.mp4');
46+
expect(a.href).toBe('blob:chrome://new-tab-page/3dc0f2b7-7773-4cd4-a397-2e43b1bba7cd');
47+
48+
expect(createSpy).toBeCalledTimes(1);
49+
expect(clickSpy).toBeCalledTimes(1);
50+
expect(removeSpy).toBeCalledTimes(1);
51+
});
52+
53+
it('should download base 64 encoded image data (downloadObject)', async () => {
54+
const img = "data:image/svg+xml;base64,";
55+
downloadObject(img, 'temp.mp4');
56+
expect(a.download).toBe('temp.svg');
57+
expect(a.href).toBe('blob:chrome://new-tab-page/3dc0f2b7-7773-4cd4-a397-2e43b1bba7cd');
58+
59+
expect(createSpy).toBeCalledTimes(1);
60+
expect(clickSpy).toBeCalledTimes(1);
61+
expect(removeSpy).toBeCalledTimes(1);
62+
});
63+
64+
it('should show a save dialog (showFileDialog)', async () => {
65+
const clickSpy = vi.spyOn(input, 'click');
66+
67+
const promise = showFileDialog('video/mp4', false);
68+
input.dispatchEvent(new Event('change'));
69+
await promise;
70+
71+
expect(input.type).toBe('file');
72+
expect(input.accept).toBe('video/mp4');
73+
expect(input.multiple).toBe(false);
74+
75+
expect(createSpy).toBeCalledTimes(1);
76+
expect(clickSpy).toBeCalledTimes(1);
77+
});
78+
});

0 commit comments

Comments
 (0)