我有一个在渲染时进行两次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
如果我只调用第一个选择器调用,则应用程序会运行,但是测试失败,因为我需要第二个调用中的数据。
任何提示都非常感谢。
答案 0 :(得分:0)
在我看来,最好通过以下方式模拟 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))