You need to sign in to do that
Don't have an account?
LaurentDelcambre
Jest for LWC: how to test focus()
Hi,
How should we test that an element received focus.
In the js controller we are testing we used:
I don't even understand what this could be, and Google doesn't seem to know either.
My gut feeling tells me that LockerService is preventing the use of document.activeElement, which is used under the hood by jest-dom toHaveFocus().
But in the end I don't know how to test focus at all
Any idea?
How should we test that an element received focus.
In the js controller we are testing we used:
const button = this.template.queryselector('xxx'); button.focus()
We know this works because it been tested through the UI ie. the focus box shows around the button.
I have tried a few things in Jest not nothign seems to work:
- Use jest-dom:
expect(button).toHaveFocus()
But only the top parent is returned by toHaveFocus().
I tested it in the smallest example possible and it just doesn't work.
- Use document.activeElement
that returns :
HTMLBridgeElement [HTMLElement] {}
I don't even understand what this could be, and Google doesn't seem to know either.
My gut feeling tells me that LockerService is preventing the use of document.activeElement, which is used under the hood by jest-dom toHaveFocus().
But in the end I don't know how to test focus at all
Any idea?
To test if an element has received focus in JavaScript, you can use the document.activeElement property to check which element currently has focus. Here's an example of how you can test this using Jest:
In this example, we create a button element, append it to the document body, and then give it focus using the focus() method. Finally, we use expect from Jest to assert that the document.activeElement is equal to the button element.
If you're working with a framework like React or Angular, you might need to use additional techniques or libraries specific to that framework for testing focus. However, the underlying concept of checking document.activeElement remains the same.
Note that document.activeElement returns the focused element in the entire document, so make sure there are no other elements receiving focus simultaneously when you perform the test.
Hope this helps !
Thank you.
First, thank you or the quick and very clear answer.
Please try the same but with a button in the html and select it with a :
element.shadowRoot.querySelector.
Your test worked, but because you didn't select anything from the shadowDom
Did you have a chance to try the same test but with selecting something exisitng in the shadow DOM?