最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

react redux - How to mock useDispatch and useSelector when testing? - Stack Overflow

programmeradmin1浏览0评论

I've just updated Redux and React-redux to the latest versions (5.0.1 and 9.2.0 respectively) and a lot of my tests fail. Up until now I've used jest.spyOn like this:

const mockUseDispatch = jest.spyOn(Redux, 'useDispatch');
const mockUseSelector = jest.spyOn(Redux, 'useSelector');

This does not work anymore, as it fails with an error that useDispatch cannot be mocked. I also tried to mock them the following way:

const mockUseDispatch = jest.fn().mockReturnValue(mockDispatch);
const mockUseSelector = jest.fn();

jest.mock('react-redux', () => ({
  ...jest.requireActual('react-redux'),
  useDispatch: mockUseDispatch,
  useSelector: () => mockUseSelector,
}));

But this also does not work, because with this, the mock doesn't seem to work and the component I'm testing is using the actual useDispatch from react-redux.

What is the correct way to mock these hooks?

发布评论

评论列表(0)

  1. 暂无评论