3

I am using a functional component that has a useRef hook. I am having a hard time mocking it. My functional component is as follows,

import { faSearch } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import * as React from 'react';
import { useRef } from 'react';

interface ISearchComponentProps {
  SearchPokemon : (id:number) => void
}

const SearchComponent: React.FunctionComponent<ISearchComponentProps> = (props) => {
  //this is the value I want to mock
  const searchInput = React.useRef<HTMLInputElement>(null)
  
  //I am "Simulating" this button click evenet
  const onSearchButtonClick = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
      executeSearch();
  }

  const onEnterPress = (event : React.KeyboardEvent<HTMLInputElement>)=>{    
    if(event.key === 'Enter'){
      executeSearch()
    }
  }

  const executeSearch = () => {
    // I cannot debug but it seems this condition is not satisfying at all            
    if(searchInput.current && searchInput.current.value){           
      props.SearchPokemon(+searchInput.current.value)
    }      
  }

  return <div className="input-group mb-3">
  <input type="number" ref={searchInput}
  className="form-control" placeholder="Search with Pokemon Id" 
  onKeyDown={onEnterPress}/>
  <div className="input-group-append">
    <button className="btn btn-outline-primary" type="button" onClick={onSearchButtonClick}>
    <i className="fas fa-camera"></i>
      <FontAwesomeIcon className="mr-2" icon={faSearch} />
      Search Pokemon      
    </button>
  </div>
</div>
};

export default SearchComponent;

my test code is as follows

import React from 'react'
import {shallow } from 'enzyme'
import SearchComponent from '../Components/SearchComponent'

const value = {
  value : 55
}

const inputValue = {
  target : value
}

const currentValue = {
  current : value
}


describe('Search Component', () => {
  beforeEach(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  })

  it('Should call mock function when the button is clicked', () =>{
    const mockSearchFunction = jest.fn();

    // I am guessing I am not setting `useRef` spy correctly.
    const mockUseRef = jest.spyOn(React, 'useRef').mockReturnValueOnce({current : currentValue});
    const component = shallow(<SearchComponent SearchPokemon={mockSearchFunction}/>);

    const searchInput = component.find('input[type="number"]').at(0);
    const searchButton = component.find('button').at(0);

    searchInput.simulate('change', inputValue);
    searchButton.simulate('click');

    //None of the below expectations work
    //expect(mockUseRef).toHaveBeenCalledTimes(1)
    expect(mockSearchFunction).toBeCalledWith(55);
  })
})

When I run the code I am presented with the below error, Error in the console

I have looked at the following two StackOverflow posts without any luck,

  1. Mocking the current Value
  2. Mocking the entire element

Not sure if its relevant but my react version = ^17.0.1

My dev dependencies for tests,

"devDependencies": {
    "@types/enzyme": "3.10.8",
    "@types/enzyme-adapter-react-16": "1.0.6",
    "enzyme": "3.11.0",
    "enzyme-adapter-react-16": "1.15.6",
    "enzyme-to-json": "3.6.1",
    "jest-fetch-mock": "3.0.3",
    "ts-jest": "26.5.1"
  }
imran chowdhury
  • 331
  • 1
  • 5
  • 18

0 Answers0