Search code examples
reactjsunit-testingjestjsreact-testing-library

Test input Search box with React testing library


I have a SearchBox component:

    function SearchBox({ search, setSearch }) {
      return (
        <div>
          <div>
            <input onChange={e => setSearch(e.target.value)} type="text" placeholder="Search..." value={search} />
          </div>
        </div>
      )
    }

I tried the following:

    describe('Input value', () => {
      it('updates on change', () => {
        const { queryByPlaceholderText } = render(<SearchBox />)
    
        const searchInput = queryByPlaceholderText('Search...')
    
        fireEvent.change(searchInput, { target: { value: 'test' } })
    
        expect(searchInput.value).toBe('test')
      })
    })

But then I get an error:

Error: Uncaught [TypeError: setSearch is not a function]

How and what can I test on this SearchBox component?


Solution

  • The issue is that setSearch props wasn't provided.

    setSearch can be provided by jest mock function.

    const setSearch = jest.fn((value) => {})
    const { queryByPlaceholderText } = render(<SearchBox setSearch={setSearch}/>)
    

    Full test code snippet:

    import React from 'react'
    import { render, fireEvent } from '@testing-library/react'
    import SearchBox from './SearchBox'
    import '@testing-library/jest-dom/extend-expect'
    
    describe('Input value', () => {
        it('updates on change', () => {
          const setSearch = jest.fn((value) => {})
          
          const { queryByPlaceholderText } = render(<SearchBox setSearch={setSearch}/>)
      
          const searchInput = queryByPlaceholderText('Search...')
      
          fireEvent.change(searchInput, { target: { value: 'test' } })
      
          expect(searchInput.value).toBe('test') // OR
          expect(setSearch).toHaveBeenCalledWith('test')
        })
      })