我有一个在渲染时多次调用 useSelector 的函数。在模拟我使用的选择器时:
jest.spyOn(Redux, 'useSelector').mockReturnValueOnce(data).mockReturnValueOnce(moreData);
这改变了在我的组件中调用钩子(Hook)的顺序。我也尝试过创建一个模拟商店并将其发送到测试中的渲染组件中,如下所示:const state = { userGuid: 'testGuid', user };
const store = mockStore(state);
jest.spyOn(Redux, 'useSelector').mockImplementation(() => store.getState());
const { getByTestId } = wrappedRender(ProfileScreen, mockProps, { store });
但这会将数据包装在我的组件无法解构的额外对象中。到目前为止,我找不到任何其他方法来模拟多个 useSelector 调用的返回值而不改变调用的钩子(Hook)的顺序。任何帮助表示赞赏。
最佳答案
依托mockReturnValueOnce
多次调用是不行的,因为顺序可能会改变。无论多少次,下面的代码都只会返回 stub 状态 useSelector
正在被调用。
import * as redux from 'react-redux'
const user = {
id: 1,
name: 'User',
}
const state = { user }
jest
.spyOn(redux, 'useSelector')
.mockImplementation((callback) => callback(state))
关于javascript - 如何在测试时正确模拟 useSelector Hook 以返回正确的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64175163/