【问题标题】:What is the correct way to mock useSelector multiple times in a component?在组件中多次模拟 useSelector 的正确方法是什么?
【发布时间】:2020-10-01 22:48:45
【问题描述】:

我有一个组件在渲染时会调用两次 useSelector。现在我已经模拟了 useSelector 并成功地从 2 个调用中返回了 2 个单独的值,它看起来像:

const Redux = require('react-redux');
const mockSelectorSpy = jest.spyOn(Redux, 'useSelector');  
mockSelectorSpy.mockReturnValueOnce(userGuid).mockReturnValueOnce(user);

这可行,我可以注销返回值,但是,这会导致测试中断并引发以下错误:

Warning: React has detected a change in the order of Hooks called by ProfileScreen. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks
    
       Previous render            Next render
       ------------------------------------------------------
    1. useState                   useContext
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
        in ProfileScreen (created by _class)
        in _class (created by _class2)
        in ThemeProvider (created by _class2)
        in _class2
        in Provider

如果我只调用第一个选择器调用,应用程序会运行,但测试失败,因为我需要来自第二个调用的数据。

非常感谢任何提示。

【问题讨论】:

  • 请提供被测代码

标签: javascript react-native unit-testing jestjs


【解决方案1】:

在我看来,最好通过以下方式模拟 Redux 存储的特定部分,这使得它独立于后续对 useSelector 的调用(这可能是由测试运行期间发生的重新渲染引起的):

  import * as redux from 'react-redux'

  const user = {
    id: 1,
    name: 'User',
  }

  const state = { user }

  jest
    .spyOn(redux, 'useSelector')
    .mockImplementation((callback) => callback(state))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    相关资源
    最近更新 更多