Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 422
meez Avatar asked Oct 13 '20 20:10

meez


1 Answers

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')
    })
  })
like image 161
ecoplaneteer Avatar answered Oct 19 '22 06:10

ecoplaneteer