This method allows you to test hook a more traditional way. You can create your test component that uses a hook, required HTML elements and test it just like you would test a component
test('TestComponent: prevents default on the first click, and does not on the second', async () => {
const user = userEvent.setup()
await render(<TestComponent />)
const button = screen.getByRole('button')
const output = screen.getByRole('status')
expect(button).toHaveTextContent(/submit/i)
await user.click(button)
expect(button).toHaveTextContent('Are you sure?')
expect(output).toHaveTextContent('yes')
await user.click(button)
expect(button).toHaveTextContent('Are you sure?')
expect(output).toHaveTextContent('no')
})
test('blurring the button starts things over', async () => {
const user = userEvent.setup()
await render(<TestComponent />)
const status = screen.getByRole('status')
const button = screen.getByRole('button')
await user.click(button)
expect(button).toHaveTextContent('You sure?')
expect(status).toHaveTextContent('Default Prevented: yes')
await user.click(document.body)
// button goes back to click me
expect(button).toHaveTextContent('Click me')
// our callback wasn't called, so the status doesn't change
expect(status).toHaveTextContent('Default Prevented: yes')
})
test('hitting "escape" on the input starts things over', async () => {
const user = userEvent.setup()
await render(<TestComponent />)
const status = screen.getByRole('status')
const button = screen.getByRole('button')
await user.click(button)
expect(button).toHaveTextContent('You sure?')
expect(status).toHaveTextContent('Default Prevented: yes')
await user.keyboard('{Escape}')
// button goes back to click me
expect(button).toHaveTextContent('Click me')
// our callback wasn't called, so the status doesn't change
expect(status).toHaveTextContent('Default Prevented: yes')
})