forked from kentcdodds/react-testing-library-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload-file.js
67 lines (56 loc) · 1.85 KB
/
upload-file.js
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
import React, {Component} from 'react'
import {render, cleanup, fireEvent} from 'react-testing-library'
afterEach(cleanup)
class UploadFile extends Component {
state = {
uploadedFileName: null,
}
handleUploadFile = e => {
const file = e.target.files[0]
this.setState({
uploadedFileName: file.name,
})
}
render() {
return (
<div>
<label for="upload-file">Upload File</label>
<input
type="file"
id="upload-file"
name="upload-file"
onChange={this.handleUploadFile}
/>
{this.state.uploadedFileName && (
<div>
You have uploaded a file named {this.state.uploadedFileName}
</div>
)}
</div>
)
}
}
test('Show the uploaded file name after the user uploads a file', () => {
const {getByLabelText, getByText} = render(<UploadFile />)
const file = new File(['(⌐□_□)'], 'chucknorris.png', {
type: 'image/png',
})
const inputEl = getByLabelText('Upload File')
// input.files is a read-only property
// so this is not allowed
// input.files = [file]
// But DOM properties are reconfigurable
// I got this while reading through a related JSDOM Github issue
// https://github.com/jsdom/jsdom/issues/1272#issuecomment-150670691
Object.defineProperty(inputEl, 'files', {
value: [file],
})
// If you want to trigger the onChange handler of a controlled component
// with a different event.target.value, sending value through
// eventProperties won't work like it does with Simulate.
// You need to change the element's value property,
// then use fireEvent to fire a change DOM event.
// https://github.com/kentcdodds/react-testing-library#fireeventeventnamenode-htmlelement-eventproperties-object
fireEvent.change(inputEl)
getByText('You have uploaded a file named chucknorris.png')
})