From a28aa616f271feeb9b0fec385a0b52522d7d9361 Mon Sep 17 00:00:00 2001 From: Ioannis Papadopoulos Date: Mon, 27 Jul 2020 11:43:40 +0100 Subject: [PATCH 1/2] fix(ByLabelText): improve error message when label is associated with non-labellable elements (#716) --- src/__tests__/element-queries.js | 108 +++++++++++++++++++++++++++++++ src/queries/label-text.js | 35 ++++++++-- 2 files changed, 139 insertions(+), 4 deletions(-) diff --git a/src/__tests__/element-queries.js b/src/__tests__/element-queries.js index 6a6df03b..7f8b5f53 100644 --- a/src/__tests__/element-queries.js +++ b/src/__tests__/element-queries.js @@ -407,6 +407,114 @@ test('label with children with no form control', () => { `) }) +test('label with non-labellable element', () => { + const {getByLabelText, queryByLabelText} = render(` +
+ +
+ Hello +
+
+ `) + + expect(queryByLabelText(/Label/)).toBeNull() + expect(() => getByLabelText(/Label/)).toThrowErrorMatchingInlineSnapshot(` +"Found a label with the text of: /Label/, however the element associated with this label (
) is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a
, you can use aria-label or aria-labelledby instead. + +
+ + +
+ + + + + +
+ + Hello + +
+ + +
+ + +
" +`) +}) + +test('multiple labels with non-labellable elements', () => { + const {getAllByLabelText, queryAllByLabelText} = render(` +
+ + + Hello + + +

+ World +

+
+ `) + + expect(queryAllByLabelText(/Label/)).toEqual([]) + expect(() => getAllByLabelText(/Label/)).toThrowErrorMatchingInlineSnapshot(` +"Found a label with the text of: /Label/, however the element associated with this label () is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a , you can use aria-label or aria-labelledby instead. + +Found a label with the text of: /Label/, however the element associated with this label (

) is non-labellable [https://html.spec.whatwg.org/multipage/forms.html#category-label]. If you really need to label a

, you can use aria-label or aria-labelledby instead. + +

+ + +
+ + + + + + + + Hello + + + + + + + +

+ + World + +

+ + +
+ + +
" +`) +}) + test('totally empty label', () => { const {getByLabelText, queryByLabelText} = render(`