模拟 useDispatch 后跟 .then() 并在功能组件中开玩笑

mock useDispatch followed by .then() with jest inside functional component

我的场景只是比这个提前了一步

我有 dispatch fn 但有 .then() 后跟。

组件:

const Testing = props => {
const [counterData, setCounterData] = useState(0)
const resData = useSelector(state => state.test)
const dispatch = useDispatch()
useEffect(() => {
    dispatch(fetchTestinData())
        .then(res => {
            console.log(res);
            setCounterData(prev => prev + 1)
        })
}, [])

return <div>
    Testing component
    <div>
        Result - {resData.title}
    </div>
    <div>
        Counter - {counterData}
    </div>
</div>

}

测试文件:

// const mockDispatch = jest.fn().mockResolvedValueOnce({json : async () => []})
const mockDispatch = jest.fn().mockImplementation(() => 
Priomise.resolve({title:'tets'}))
jest.mock('react-redux', () => ({
    ...jest.requireActual('react-redux'),
    useDispatch: () => mockDispatch
}))

describe('<Testing />', function () {
    const getComponent = (state) => <Provider store={store}>
        <Testing />
    </Provider>

    it('testing success api', () => {
        // window.fetch = jest.fn().mockResolvedValueOnce({title: 'testing title'})
        render(getComponent())
        screen.debug()
        // expect(mockDispatch).toBeCalledTimes(1)
    })

})

如果我只使用 jest.fn() 得到相同的错误以及模拟实现。 Error screenshot

模拟 fn 实现中缺少某些内容。 请帮助。搜索了很多但没有运气。

显然是在开玩笑 docs are a bit misleading about the possibility to use previously defined variables in a mock module factory: that is just not possible

所以您的问题的解决方案就是将您的 mockDispatch 实现移动到模块工厂中:

jest.mock('react-redux',
  () => ({
    ...jest.requireActual('react-redux'),
    useDispatch: () => jest.fn().mockImplementation(() =>
      Promise.resolve({ title: 'test' }))
  })
)