-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathuseSingleFileInput.spec.ts
More file actions
71 lines (55 loc) · 2.49 KB
/
useSingleFileInput.spec.ts
File metadata and controls
71 lines (55 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { renderHook, act } from '@testing-library/react';
import { useSingleFileInput } from './useSingleFileInput';
afterEach(() => {
document.body.innerHTML = '';
});
describe('useSingleFileInput', () => {
it('should create an input element and append it to the body', () => {
const onSetFile = jest.fn();
renderHook(() => useSingleFileInput(onSetFile));
const input = document.createElement('input');
input.type = 'file';
input.style.display = 'none';
document.body.appendChild(input);
expect(input).toBeDefined();
expect((input as HTMLInputElement).style.display).toBe('none');
});
it('should set the accept attribute based on fileType option', () => {
const onSetFile = jest.fn();
renderHook(() => useSingleFileInput(onSetFile, 'image', { fileType: 'video/*' }));
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
expect(input.getAttribute('accept')).toBe('video/*');
});
it('should use default accept attribute if not provided', () => {
const onSetFile = jest.fn();
renderHook(() => useSingleFileInput(onSetFile));
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
expect(input.getAttribute('accept')).toBe('image/*');
});
it('should trigger click on the input when calling onClick', () => {
const onSetFile = jest.fn();
const { result } = renderHook(() => useSingleFileInput(onSetFile));
const [onClick] = result.current;
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
const clickSpy = jest.spyOn(input, 'click');
act(() => {
onClick();
});
expect(clickSpy).toHaveBeenCalled();
});
it('should call onSetFile when a file is selected', () => {
const onSetFile = jest.fn();
renderHook(() => useSingleFileInput(onSetFile, 'test-field'));
const input = document.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['foo'], 'foo.txt', { type: 'text/plain' });
Object.defineProperty(input, 'files', {
value: [file],
});
act(() => {
input.dispatchEvent(new Event('change'));
});
expect(onSetFile).toHaveBeenCalledWith(file, expect.any(FormData));
const formData = onSetFile.mock.calls[0][1] as FormData;
expect(formData.get('test-field')).toBe(file);
});
});