0

I am trying to write a jest test for my inputBox component that include a button. Have a function 'onClick' as a prop inside this component.

        <inputBox
            placeholder={'Type here..'}
            onClick={() => {inputRef.current.blur()}}
            button={true}
            ref={inputRef}
        />

I want to test the event 'inputBox is blur once I click the button'. Below is the test code:

it('invokes blur after click button',() => {
    const onBlurSpy = jest.fn();
    const { getAllByRole } = render(inputBox);
    fireEvent.click(getAllByRole('button'))
    expect(onBlurSpy).toHaveBeenCalled();
}); 

Receive below error:

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

Any idea for this?

dosu
  • 41
  • 2
  • 8

1 Answers1

0

The onBlurSpy mock function isn't being called in the test because it isn't attached to the inputBox component. The blur function would likely need to be passed in as a prop to the component if you wanted to use jest.fn() to mock it.

If you want to check if the blur function has been called without adjusting the component's props, I'd recommend using Jest's spyOn method.

Give the function you want to spy on a name so it can be referenced:

<inputBox
     ...
     onClick={this.blurFunction}
     ...
/>

Then use Jest's spyOn function in the test:

const onBlurSpy = jest.spyOn(inputBox.instance(), "blurFunction")

I'd also recommend reading this answer from a related StackOverflow question for some additional context.

jedeen
  • 178
  • 2
  • 8