forked from testing-library/user-event
/
clear.js
102 lines (91 loc) 路 2.62 KB
/
clear.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '../../src'
test.each(['input', 'textarea'])('should clear text in <%s>', type => {
const onChange = jest.fn().mockImplementation(event => {
// Verify that `event.target`'s value is correct when the event handler is
// fired.
expect(event.target).toHaveProperty('value', '')
})
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
value: 'Hello, world!',
}),
)
const input = screen.getByTestId('input')
userEvent.clear(input)
expect(input.value).toBe('')
expect(onChange).toHaveBeenCalledTimes(1)
})
test.each(['input', 'textarea'])(
'should not clear when <%s> is disabled',
type => {
const text = 'Hello, world!'
const onChange = jest.fn().mockImplementation(event => {
// Verify that `event.target`'s value is correct when the event handler is
// fired.
expect(event.target).toHaveProperty('value', '')
})
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
value: text,
disabled: true,
}),
)
const input = screen.getByTestId('input')
userEvent.clear(input)
expect(input).toHaveProperty('value', text)
expect(onChange).toHaveBeenCalledTimes(0)
},
)
test.each(['input', 'textarea'])(
'should not clear when <%s> is readOnly',
type => {
const onChange = jest.fn()
const onKeyDown = jest.fn()
const onKeyUp = jest.fn()
const text = 'Hello, world!'
render(
React.createElement(type, {
'data-testid': 'input',
onChange,
onKeyDown,
onKeyUp,
value: text,
readOnly: true,
}),
)
const input = screen.getByTestId('input')
userEvent.clear(input)
expect(onKeyDown).toHaveBeenCalledTimes(1)
expect(onKeyUp).toHaveBeenCalledTimes(1)
expect(onChange).toHaveBeenCalledTimes(0)
expect(input).toHaveProperty('value', text)
},
)
;['email', 'password', 'number', 'text'].forEach(type => {
test.each(['input', 'textarea'])(
`should clear when <%s> is of type="${type}"`,
inputType => {
const onChange = jest.fn()
const value = '12345'
const placeholder = 'Enter password'
const element = React.createElement(inputType, {
value,
placeholder,
type,
onChange,
})
render(element)
const input = screen.getByPlaceholderText(placeholder)
expect(input.value).toBe(value)
userEvent.clear(input)
expect(input.value).toBe('')
expect(onChange).toHaveBeenCalledTimes(1)
},
)
})