0

我想测试父组件,但我想在没有 redux 的情况下做到这一点。我有问题,因为我有错误:

不变违规:在“Connect(MarkerList)”的上下文或道具中找不到“store”。要么将根组件包装在 a 中,要么将“store”作为道具显式传递给“Connect(MarkerList)”。

我的父组件:

export class Panel extends React.Component {
  constructor(props) {

  }

  componentDidUpdate(prevProps) {
   ...
  }

  handleCheckBox = event => {
   ...
  };

  switchPanelStatus = bool => {
    ...
  };

  render() {
   ...
  }
}

const mapDispatchToProps = {
  isPanelSelect
};

export const PanelComponent = connect(
  null,
  mapDispatchToProps
)(Panel);

我的子组件:

export class MarkerList extends Component {
  constructor(props) {
      ...   
    };
  }

  componentDidMount() {
   ...
  }

  componentDidUpdate() {
   ...
  }

  onSelect = (marker, id) => {
   ...
  }

  render() {
  ...
  }
}

const mapStateToProps = state => ({
  ...
});

const mapDispatchToProps = {
 ...
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(MarkerList);

面板测试文件:

import '@testing-library/jest-dom'
import "@testing-library/react"
import React from 'react'
import {render, fireEvent, screen} from '@testing-library/react'
import {Panel} from '../Panel';


test("test1", async () => {

  const isPanelSelect = jest.fn();
  const location = {
    pathname: "/createMarker"
  }

  const {getByText} = render(  <Panel isPanelSelect={isPanelSelect} location={location} />)
})

我尝试将商店设置为面板组件的道具或通过提供程序将其包装在我的测试文件中,但这对我没有帮助。

4

1 回答 1

0

react-redux没有store. 您可以通过上下文或道具(通常在测试中)提供它。您可以在测试中提供模拟版本。主要问题是这两个组件都需要 Redux。如果作为道具提供,您必须手动将上下文转发给孩子。另一种解决方案是将组件挂载在 Redux 感知树中:

import { Provider } from "react-redux";

test("test1", async () => {
  const { getByText } = render(
    <Provider store={createFakeStore()}>
      <Panel isPanelSelect={isPanelSelect} location={location} />
    </Provider>
  );
});
于 2020-04-20T14:41:58.520 回答