fetchSuggestions这个方法怎么监听啊?

来源:9-11 完美收尾 - AutoComplete 添加单元测试

菜鸟x

2020-06-05

 describe('fetchSuggestion', () => {
    beforeEach(() => {
      jest.useFakeTimers()
    })
    it('async fetchSuggestions should works fine', async () => {
      cleanup()
      const fn = jest.fn()
      const wrapper = render(<AutoComplete fetchSuggestions={fn} placeholder="auto_complete"/>)
      inputNode = wrapper.getByPlaceholderText('auto_complete') as HTMLInputElement
      await act(() => {
        fireEvent.change(inputNode, { target: { value: 'a' } })
        jest.runAllTimers()
        expect(fn).toBeCalledTimes(1)
      })
    })
  })

我改动了inputValue值,但是fn没有捕获到函数的调用

写回答

1回答

张轩

2020-06-06

同学 我是这么写的 你可以对比一下看看

const asyncProps: AutoCompleteProps = {
    //fetchSuggestions: (query) => {return Promise.resolve(testArray.filter(item => item.value.includes(query)))},
    fetchSuggestions: jest.fn(query => {return Promise.resolve(testArray.filter(item => item.value.includes(query)))},),
    onSelect: jest.fn(),
    placeholder: 'auto-complete'
}
const wrapper = render(<AutoComplete {...asyncProps}/>)
const inputNode = wrapper.getByPlaceholderText('auto-complete') as HTMLInputElement
fireEvent.change(inputNode, {target: { value: 'a'}})
await wait(() => {
    expect(asyncProps.fetchSuggestions).toHaveBeenCalled()
    expect(wrapper.queryByText('ab')).toBeInTheDocument()
})


0
3
菜鸟x
回复
张轩
好的。非常感谢老师的解答。
2020-06-08
共3条回复

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2124 学习 · 959 问题

查看课程