Skip to content

Commit b7cf451

Browse files
author
sethbarton
committed
fix: userEvent.click() ignores hidden elements (testing-library#1145)
1 parent d7483f0 commit b7cf451

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,6 @@ dist
77
# when working with contributors
88
package-lock.json
99
yarn.lock
10+
11+
# don't commit JetBrains IDE configs
12+
.idea

src/convenience/click.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import {type PointerInput} from '../pointer'
22
import {type Instance} from '../setup'
3+
import {CLICKABLE_SELECTOR} from '../utils/click/selector'
34

45
export async function click(this: Instance, element: Element): Promise<void> {
6+
if (!isClickableElement(element)) return
7+
58
const pointerIn: PointerInput = []
69
if (!this.config.skipHover) {
710
pointerIn.push({target: element})
@@ -15,12 +18,18 @@ export async function dblClick(
1518
this: Instance,
1619
element: Element,
1720
): Promise<void> {
21+
if (!isClickableElement(element)) return
1822
return this.pointer([{target: element}, '[MouseLeft][MouseLeft]'])
1923
}
2024

2125
export async function tripleClick(
2226
this: Instance,
2327
element: Element,
2428
): Promise<void> {
29+
if (!isClickableElement(element)) return
2530
return this.pointer([{target: element}, '[MouseLeft][MouseLeft][MouseLeft]'])
2631
}
32+
33+
export function isClickableElement(element: Element) {
34+
return element.matches(CLICKABLE_SELECTOR)
35+
}

src/utils/click/selector.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const CLICKABLE_SELECTOR = ['*:not([style*="hidden"])'].join(', ')

tests/convenience/click.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,23 @@ describe.each([
3838
expect(getEvents('click')).toHaveLength(clickCount)
3939
})
4040

41+
test('can not click hidden elements', async () => {
42+
const {element, getEvents, user} = setup(
43+
` <button
44+
style="visibility: hidden"
45+
>
46+
Click me!
47+
</button>`,
48+
{
49+
pointerEventsCheck: PointerEventsCheckLevel.Never,
50+
},
51+
)
52+
53+
await user[method](element)
54+
55+
expect(getEvents('click')).toHaveLength(0)
56+
})
57+
4158
if (method === 'click') {
4259
test('skip hover', async () => {
4360
const {element, getEvents, user} = setup(`<div></div>`, {

0 commit comments

Comments
 (0)