浅复制一个具有在酶中提供的存储的React组件

问题描述 投票:0回答:1

[尝试shallow(<LoginForm />)时,出现以下错误Invariant Violation: Could not find react-redux context value; please ensure the component is wrapped in a <Provider>。因此,为了解决此问题,我尝试了:

const wrapper = shallow(
    <Provider store={store}>
        <LoginForm />
    </Provider>
);

但是,调试输出为:

<ContextProvider value={{...}}>
  <LoginForm />
</ContextProvider>

但是我也想呈现LoginForm。我尝试解决此问题的其他方法:

wrapper.find(LoginForm).shallow();

shallow(
    <Provider store={store}>
        <LoginForm />
    </Provider>
).dive();

wrapper.find(LoginForm).shallow();

shallow(<LoginForm />, {
    wrappingComponent: Provider,
    wrappingComponentProps: { store }
});

但是所有这些都会导致上述相同的错误。使用shallow方法时,如何解决此问题?另外,LoginForm使用了React钩子,包括useSelect钩子,因此将存储传递到组件prop不是我要的解决方案。

reactjs redux jestjs react-hooks enzyme
1个回答
0
投票

您可以模拟useSelector,也方便模拟选择器功能

import React from 'react';
import { mount, shallow } from 'enzyme';
import { getIsAuthorized } from 'modules/auth/reducer';
import SignIn from '../SignIn';

jest.mock('modules/auth/reducer');

jest.mock('react-redux', () => {
  const RealModule = jest.requireActual('react-redux');
  return {
    ...RealModule,
    useSelector: (fn) => fn(),
  };
});

interface SetupProp {
  isAuthorized: boolean;
}

describe('Page: SignIn', () => {
  const setupWrapper = ({ isAuthorized }: SetupProp) => {
    (getIsAuthorized as jest.Mock).mockReturnValue(isAuthorized);
    return shallow(<SignIn />);
  };

  test('should render form', () => {
    const wrapper = setupWrapper({ isAuthorized: false });
    expect(wrapper).toMatchSnapshot();
  });
});

登录组件:

  const SignIn: FunctionComponent = () => {
   //...
       const isAuthorized = useSelector(getIsAuthorized);
   //...
  }
© www.soinside.com 2019 - 2024. All rights reserved.