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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
import fileUpload, { getFilename, validateImageName } from '~/lib/utils/file_upload';
describe('File upload', () => {
beforeEach(() => {
setFixtures(`
<form>
<button class="js-button" type="button">Click me!</button>
<input type="text" class="js-input" />
<span class="js-filename"></span>
</form>
`);
});
describe('when there is a matching button and input', () => {
beforeEach(() => {
fileUpload('.js-button', '.js-input');
});
it('clicks file input after clicking button', () => {
const btn = document.querySelector('.js-button');
const input = document.querySelector('.js-input');
jest.spyOn(input, 'click').mockReturnValue();
btn.click();
expect(input.click).toHaveBeenCalled();
});
it('updates file name text', () => {
const input = document.querySelector('.js-input');
input.value = 'path/to/file/index.js';
input.dispatchEvent(new CustomEvent('change'));
expect(document.querySelector('.js-filename').textContent).toEqual('index.js');
});
});
it('fails gracefully when there is no matching button', () => {
const input = document.querySelector('.js-input');
const btn = document.querySelector('.js-button');
fileUpload('.js-not-button', '.js-input');
jest.spyOn(input, 'click').mockReturnValue();
btn.click();
expect(input.click).not.toHaveBeenCalled();
});
it('fails gracefully when there is no matching input', () => {
const input = document.querySelector('.js-input');
const btn = document.querySelector('.js-button');
fileUpload('.js-button', '.js-not-input');
jest.spyOn(input, 'click').mockReturnValue();
btn.click();
expect(input.click).not.toHaveBeenCalled();
});
});
describe('getFilename', () => {
it('returns file name', () => {
const file = new File([], 'test.jpg');
expect(getFilename(file)).toBe('test.jpg');
});
});
describe('file name validator', () => {
it('validate file name', () => {
const file = new File([], 'test.jpg');
expect(validateImageName(file)).toBe('test.jpg');
});
it('illegal file name should be rename to image.png', () => {
const file = new File([], 'test<.png');
expect(validateImageName(file)).toBe('image.png');
});
});
|