我有一个<InputSearch/>
组件作为<input type="search">
周围的包装,当用户按下onSearch
时,它会收到enter
个道具作为回调。我如何测试将使用react-testing-library调用回调?
我要测试的组件:
const Search = ({ className, onSearch, placeholder }) => {
const [searchValue, setSearchValue] = useState('')
const handleChange = e => {
setSearchValue(e.target.value)
}
const search = (value, e) => {
onSearch(value)
}
return (
<SearchInput
data-testid="search-input"
placeholder={placeholder}
onChange={handleChange}
onSearch={search}
/>
)
}
我尝试过:
describe('Search', () => {
const fakeOnSearch = jest.fn()
const fakeProps = {
className: 'fake-class-name',
onSearch: fakeOnSearch,
placeholder: 'fakesearch'
}
const { getByTestId, getByText, getByPlaceholderText } = render(<Search {...fakeProps} />)
const node = getByTestId('search-input')
afterEach(cleanup)
it('calls onSearch callback', () => {
fireEvent.keyPress(node, { key: "Enter", code: 13, charCode: 13 })
expect(fakeOnSearch).toBeCalledTimes(1)
})
})
测试结果:
expect(jest.fn()).toBeCalledTimes(1)
Expected mock function to have been called one time, but it was called zero times