如何测试包装在另一个连接组件中的连接组件?

时间:2019-05-10 07:08:01

标签: javascript reactjs unit-testing redux jestjs

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

MyComp.js

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

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

<Wrapper>处:

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 <Provider> or explicitly pass "store" as a prop to "Connect(AppWrapper)"

之所以会这样,是因为<Wrapper>已连接到我的<MyComp>组件中,但是我不确定如何测试 just ,即使后者被包装在已连接的组件中组件。

2 个答案:

答案 0 :(得分: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组件。

答案 1 :(得分:0)

尝试一下:

import configureMockStore from 'redux-mock-store';

const store = mockStore({});
const component = renderer.create(<Provider store={store}><Login /></Provider>);
相关问题