【问题标题】:How to test a connected component wrapped in another connected component?如何测试包装在另一个连接组件中的连接组件?
【发布时间】:2019-09-28 01:23:11
【问题描述】:

我想测试我的纯组件,所以我这样做:

MyComp.js

export MyComp = props => {
  return (
    <Wrapper>Content</Wrapper>
  )
}

const MyCompConn = connect()(MyComp);
export default MyCompConn;

&lt;Wrapper&gt;:

export Wrapper = ({children}) => {
  return (
    <div>{children}</div>
  )
}

const WrapperConn = connect()(Wrapper);
export default WrapperConn;

MyComp.test.js

import React from 'react';
import renderer from 'react-test-renderer';

import { MyComp } from '../../MyComp';


describe('With Snapshot Testing', () => {
  it('renders!"', () => {
    const component = renderer.create(<Login />);
    const tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
});

现在,当我运行 yarn test 时,我得到了这个错误:

Invariant Violation: Could not find "store" in either the context or props of "Connect(AppWrapper)". Either wrap the root component in a &lt;Provider&gt; or explicitly pass "store" as a prop to "Connect(AppWrapper)"

发生这种情况是因为&lt;Wrapper&gt; 连接在我的&lt;MyComp&gt; 组件中,但我不确定如何测试只是后者,即使它包装在连接的组件上。 p>

【问题讨论】:

    标签: javascript reactjs unit-testing redux jestjs


    【解决方案1】:

    试试这个:

    import configureMockStore from 'redux-mock-store';
    
    const store = mockStore({});
    const component = renderer.create(<Provider store={store}><Login /></Provider>);
    

    【讨论】:

    • 有没有办法在没有模拟商店的情况下做到这一点?
    • 另外,这不起作用,我得到TypeError: store.getState is not a function
    【解决方案2】:

    要在不使用模拟存储的情况下测试我们的组件,我们可以使用 Jest 模拟 react-redux 本身的连接。 PFB 示例:

    
    import React from 'react';
    import renderer from 'react-test-renderer';
    
    import { MyComp } from '../../MyComp';
    
    jest.mock('react-redux', () => ({
      connect: () => {
        return (component) => {
          return component
        };
      }
    }));
    
    describe('With Snapshot Testing', () => {
      it('renders!"', () => {
        const component = renderer.create(<Login />);
        const tree = component.toJSON();
        expect(tree).toMatchSnapshot();
      });
    });
    

    现在,这将直接渲染 Wrapper 组件,而不是 connected Wrapper 组件。

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 2021-05-13
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 2017-11-26
      • 2014-10-19
      • 2020-07-19
      • 2017-03-29
      相关资源
      最近更新 更多