React Mocha-chai 测试无法从道具中识别商店

mha*_*tch 5 javascript mocha.js chai reactjs redux

我对 Redux 连接的 React 组件进行了 Mocha-chai 测试。为了将 Redux 存储传递给测试组件,我在测试文件中创建它并将其作为 prop 传递,但测试抛出以下错误:

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

这是测试:

import React from 'react';
import ReactDOM from 'react-dom';
import { 
  renderIntoDocument,
  scryRenderedComponentsWithType
} from 'react-dom/test-utils';
import Project from '../../src/components/Project';
import { expect } from 'chai';
import { createStore } from 'redux';
import reducer from '../../src/reducers/reducers';

const store = createStore(reducer);

const component = renderIntoDocument(
  <Project 
    store={ store } 
    project={
      {
        "name": "MyName",
        "img": "path.jpg",
        "img_alt": "alt desc",
        "description": "lorem ipsum",
        "github": "repository",
        "link": "website.com"
      }
    } />
);

describe('Project', () => {

  // tests ...

});
Run Code Online (Sandbox Code Playgroud)

这是 React 组件:

import React from 'react';
import ProjectImage from './ProjectImage';
import ProjectText from './ProjectText';
import { connect } from 'react-redux';
import * as actions from '../actions/actions';

export const Project = React.createClass({

  getProject: function() {
    return this.props.project || {};
  },

  handleClick: function(event) {
    this.props.dispatch(actions.showModal(true));
    this.props.dispatch(
      actions.setModalContent(this.getProject())
    );
  },

  render: function() {
    return (
      <div className="project">

        <ProjectImage 
          img={ this.getProject().img } 
          imgAlt={ this.getProject().img_alt }
          link={ this.getProject().link } />

        <ProjectText 
          projectName={ this.getProject().name } 
          tagline={ this.getProject().tagline } 
          description={ this.getProject.description }
          github={ this.getProject().github }
          webLink={ this.getProject().link } 
          openModal={ this.handleClick } />

      </div>
    );
  }

});

export default connect()(Project);
Run Code Online (Sandbox Code Playgroud)

chu*_*uve 0

为什么你使用没有或功能connect的组件?ProjectmapStateToPropsmapDispatchToProps

\n\n

但是...没有必要将包装的组件测试到connect. \n您所需要的只是测试普通Project组件。

\n\n

如何导出这两个组件?\xe2\x80\x93对于同一问题,请点击此链接。

\n