Skip to content

Commit

Permalink
update hook tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ktravers authored Feb 5, 2025
1 parent 8b89620 commit 9b745ba
Showing 1 changed file with 47 additions and 3 deletions.
50 changes: 47 additions & 3 deletions packages/react/src/__tests__/hooks/useOpenAndCloseFocus.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, {useRef} from 'react'
import React, {useRef, useState} from 'react'
import {render, waitFor} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {useOpenAndCloseFocus} from '../../hooks/useOpenAndCloseFocus'

const Component = () => {
Expand Down Expand Up @@ -39,16 +40,59 @@ const ComponentTwo = () => {
)
}

it('should focus element passed into function', async () => {
const ComponentThree = () => {
const [isOpen, setIsOpen] = useState(true)

const containerRef = useRef<HTMLDivElement>(null)
const returnFocusRef = useRef<HTMLButtonElement>(null)
const noButtonRef = useRef<HTMLButtonElement>(null)
useOpenAndCloseFocus({containerRef, initialFocusRef: noButtonRef, returnFocusRef, preventFocusOnOpen: true})

return (
<>
<button ref={returnFocusRef} type="button" onClick={() => setIsOpen(!isOpen)}>
toggle
</button>
{isOpen && (
<div ref={containerRef}>
<button type="button">yes</button>
<button ref={noButtonRef} type="button">
no
</button>
</div>
)}
</>
)
}

it('should focus initialFocusRef element passed into function', async () => {
const {getByText} = render(<Component />)
await waitFor(() => getByText('no'))
const noButton = getByText('no')
expect(document.activeElement).toEqual(noButton)
})

it('should focus first element when nothing is passed', async () => {
it('should focus first element when no initialFocusRef prop is passed', async () => {
const {getByText} = render(<ComponentTwo />)
await waitFor(() => getByText('yes'))
const yesButton = getByText('yes')
expect(document.activeElement).toEqual(yesButton)
})

it('should not focus any element if preventFocusOnOpen prop is passed', async () => {
render(<ComponentThree />)
expect(document.activeElement).toEqual(document.body)
})

it('should focus returnFocusRef element when rendered', async () => {
const user = userEvent.setup()
const {getByText} = render(<ComponentThree />)

await waitFor(() => getByText('toggle'))
const toggleButton = getByText('toggle')

// Close container, so containerRef and initialFocusRef elements are no longer rendered
await user.click(toggleButton)

expect(document.activeElement).toEqual(toggleButton)
})

0 comments on commit 9b745ba

Please sign in to comment.