簡體   English   中英

在 Enzyme 中使用提供的 store 淺復制 React 組件

[英]Shallow copy a React component with a provided store in Enzyme

當我嘗試shallow(<LoginForm />)我收到以下錯誤Invariant Violation: Could not find react-redux context value; please ensure the component is wrapped in a <Provider> 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使用反應鈎子,包括useSelect鈎子,因此將存儲傳遞給我的組件道具不是我正在尋找的解決方案。

您可以模擬 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);
   //...
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM