繁体   English   中英

使用jest和酶测试高阶组件

[英]Testing Higher Order Components using jest and 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)". 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编写为匿名函数的方式有关,我无法导出连接函数,但我不确定如何修复它。 任何帮助/建议将不胜感激。

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();
  });
});

您没有将商店传递给您正在测试的组件。

以下文章是如何设置测试的一个很好的资源https://medium.com/@visualskyrim/test-your-redux-container-with-enzyme-a0e10c0574ec

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帮助程序并将这些支持传递给正在测试的组件(例如历史记录)。

这是在错误消息建议时解决的,即使用Provider

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM