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?
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')
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With