I am facing issues in triggering the Enter event on button and testing the method associated with the event. I have two buttons refine search and close button on my component, so trying to implement the same associated click functionality with Enter key as well. For this, I am calling keyDownHandler method onKeydown event and call respective methods.
This is my method in component
const keyDownHandler = event = {
const targetValue = event.target.id
if(event.key === 'Enter' || event.keyCode=== 13){
if(targetvalue === 'someid1'){
return executeHandleRefineSearch()
}
if(targetvalue === 'someid2'){
return executeHandleClose()
}
}
}
My test case is
import React from 'react'
import { cleanup, render, fireEvent } from '@testing-library/react'
import ReactDOM from 'react-dom'
import '@testing-library/jest-dom/extend-expect'
import myButtonGroup from '.'
afterEach(cleanup)
beforeAll(() => {})
describe('myButtonGroup ', () => {
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<myButtonGroup/>, div)
})
it('enter key on clear button only should trigger executeHandleRefineSearch', () => {
const { container } = render(<myButtonGroup />)
const executeHandleRefineSearchMock = jest.fn()
const event = {
key: 'Enter',
code: 'Enter',
keyCode: 13,
charCode: 13,
target: { id: 'someid1' }
}
const refineSearchButton = container.querySelector(
'#someid1'
)
fireEvent.keyDown(refineSearchButton, event)
expect(executeHandleRefineSearchMock ).toHaveBeenCalled()
})
})
I am getting below error expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
Any suggestion would be greatly appreciated.
Updated test case after the suggestion
it('enter key on clear button only should trigger executeHandleRefineSearch', () => {
const executeHandleRefineSearchMock = jest.fn()
const { container } = render(
<myButtonGroup
handleClearSearchValues={executeHandleRefineSearchMock}
/>
)
const event = {
key: 'Enter',
keyCode: 13,
charCode: 13,
target: { id: 'someid' }
}
const refineSearchButton = container.querySelector(
'#someid'
)
refineSearchButton .focus()
userEvent.click(refineSearchButton, event)
expect(handleClearSearchValuesMock).toHaveBeenCalled()
})