我有一个SearchBox组件:
function SearchBox({ search, setSearch }) {
return (
<div>
<div>
<input onChange={e => setSearch(e.target.value)} type="text" placeholder="Search..." value={search} />
</div>
</div>
)
}
我尝试了以下操作:
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')
})
})
但是我得到一个错误:
错误:未捕获[TypeError:setSearch不是函数]
如何在此SearchBox组件上进行测试?
答案 0 :(得分:0)
问题是没有提供setSearch
道具。
setSearch
可以由笑话模拟功能提供。
const setSearch = jest.fn((value) => {})
const { queryByPlaceholderText } = render(<SearchBox setSearch={setSearch}/>)
完整的测试代码段:
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')
})
})