如何解决与 redux store 相关的 "Invariant Violation" 错误?

How to resolve "Invariant Violation" error, related to redux store?

我正在尝试进行 DOM 测试,以检查是否在单击按钮时打开对话框。然后我得到这个错误

Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , or >explicitly pass "store" as a prop to "Connect(Photos)".

我使用了 jest,我的组件使用

连接到 redux store

export default connect(mapToProps)(Photos);

AccessoriesPhotos.js

class Photos extends React.Component {
    constructor() {
        super();
        this.state = {
            open: false,

        }
        this.handleOpen = this.handleOpen.bind(this);
    }
    handleOpen = () => {
        this.setState({ open: true });
    };

    render (){
        return (....)
    }

    const mapToProps = (state) => {
        return {
          Search: state.Search,
          App: state.App
        }
      }


    export default connect(mapToProps)(Photos);
}

AccessoriesPhotos.test.js

import React from 'react';
import Enzyme, {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Photos } from '../../../Photos/Bike/AccessoriesPhotos';

Enzyme.configure({adapter: new Adapter()});

it('Dialog box opens after click', () => {

  const openDialogButton = shallow(<Photos open="true" close="false" />);

  expect(openDialogButton.text()).toEqual('true');

  openDialogButton.find('input').simulate('change');

  expect(openDialogButton.text()).toEqual('false');
});

这就是我得到的结果。

Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , or >explicitly pass "store" as a prop to "Connect(Photos)".strong text

您的 Photos 组件没有得到 store,因为您没有在测试中将其作为 Provider 的子组件呈现。如果您也将其包装在 Provider 中进行测试,它将按预期工作。

const openDialogButton = shallow(
  <Provider store={store}>
    <Photos open="true" close="false" />
  </Provider>
);