使用玩笑和酶测试高阶组件

时间:2018-11-19 20:02:52

标签: javascript reactjs unit-testing jestjs enzyme

我为高阶组件创建了一个测试,但是每当运行该测试时,都会出现此错误:Invariant Violation: Could not find "store" in either the context or props of "Connect(ExampleComponent)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(ExampleComponent)".

我认为这可能与将HOC组成匿名函数的方式有关,在该函数中我无法导出connect函数,但不确定如何解决它。任何帮助/建议将不胜感激。

HOCExample.js

import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';

export default ComposedComponent => {
  class ExampleComponent extends PureComponent {
    //some logic here
    render() {
      return (
          <div style={{ marginTop: 80 }}>
            <ComposedComponent {...this.props} />
          </div>
        )
      );
    }
  }

  ExampleComponent.contextTypes = {
    test: PropTypes.func.isRequired,
    example: PropTypes.func.isRequired
  };

  const mapStateToProps = ({ example }) => ({
    count: example.count,
  });

  const mapDispatchToProps = { getExampleCount };

  return connect(
    mapStateToProps,
    mapDispatchToProps
  )(ExampleComponent);
};

HOCExample.test.js

import React from 'react';
import { shallow } from 'enzyme;'
import { default as HOCExample } from '../HOCExample';

const TestComponent = () => <h1>Test</h1>

const ComponentRendered = HOCExample(TestComponent)

describe('HOCExample', () => {
  const props = {
    example: []
  };

  it('renders authorized component', () => {
    const wrapper = shallow(<ComponentRendered {...props} />);
    expect(wrapper).toMatchSnapshot();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });
});

2 个答案:

答案 0 :(得分:2)

您没有将存储传递给要测试的组件。

以下文章是有关如何设置测试http://www.facebook.com/GeracaoInvencive

的很好的资源

redux-mock-store对模拟商店很有帮助。

import configureMockStore from 'redux-mock-store';
const createMockStore = configureMockStore();
const defaultState = {} // whatever you want the default store state to be
const store = createMockStore(defaultState);

//helper wrapper function
const giveStore = (component, store) => {
  const context = {
    store,
  };
  return shallow(component, { context });
};

const wrapper = giveStore(<ComponentRendered {...props} />, store);

您可以将其重构为一个单独的帮助文件,并使其可重用,例如将更多选项传递到GiveStore帮助器中,并将这些道具传递到要测试的组件(例如历史记录)。

答案 1 :(得分:1)

这是根据错误消息所建议的方式解决的,即使用Provider

const wrapper = shallow(<Provider store={dummyStore}><ComponentRendered {...props} /></Provider>);

dummyStore是符合情况的Redux存储,例如,具有example属性。

相关问题