1

I am trying to find to get jest to tab event to the next element but document.dispatchEvent doesn't seem to be working. I'm curious as to rather or not if the code i'm running is correct?


import { logger } from "@js-ecom-mfe/logger";
...

jest.mock("@js-ecom-mfe/logger");
describe("tests keyboard focus constrain", () => {

  
  it("tab press", async() => {
    // this is the keyboardtabevent
    const tabEvent = new KeyboardEvent( 'keydown', { keyCode: 9,bubbles: true} )

// this is how i'm trying to fire the tab event

    document.dispatchEvent(tabEvent)
   
  })
  
})
TylerH
  • 20,799
  • 66
  • 75
  • 101
tg marcus
  • 157
  • 2
  • 13
  • I believe you cannot do that. You can dispatch events for the web application under test to handle them, but jest is not a user agent, it has no logic for finding the next focusable element and do that on behave of some imaginary user. /: – Andy Jul 06 '22 at 15:01
  • See also https://stackoverflow.com/questions/7208161/focus-next-element-in-tab-index – Andy Jul 06 '22 at 15:08
  • So what's the best way to test for the focus if not jest then ? – tg marcus Jul 06 '22 at 15:17
  • What would you like to assert? – Andy Jul 06 '22 at 16:38
  • as long as its a javascript testing library that can test focus and dispatch keyboard events in the test then i should be fine – tg marcus Jul 06 '22 at 20:10
  • I mean what are you trying to test? Which behaviour of the product? If you want to test that a certain element is next in the tab order, you could do so by testing the conditions necessary for that: f..e. it‘s an [element that can receive focus](https://stackoverflow.com/questions/1599660/which-html-elements-can-receive-focus) or has tabindex=0, and either is one of those elements or has explicitly a keyboard handler attached. Lighthouse and other audit tools do these tests, and for accessibility it would probably be better to include such an audit in your build than to reinvent these tests. – Andy Jul 07 '22 at 06:47

0 Answers0