10

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?

1
  • You need to pass in the props the component defines when you render it. And don't test the value of the input, it's not actually that component's job to update it, test the callback was invoked with the right value. Commented Oct 13, 2020 at 20:15

1 Answer 1

13

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')
    })
  })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.