簡體   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