React Mocha-chai测试不识别来自道具的商店

时间:2017-08-15 16:50:44

标签: javascript reactjs redux mocha chai

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

  

不变违规:无法在上下文中找到“存储”或   “连接(项目)”的道具。将根组件包装在一个   < Provider>,或明确地将“store”作为prop传递给   “连接(项目)”。

以下是测试:

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 ...

});

这是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);

2 个答案:

答案 0 :(得分:0)

为什么在没有connectProject函数的情况下将mapStateToProps用于mapDispatchToProps组件?

然而......没有必要将包裹的组件测试到connect。 您所需要的只是测试普通Project组件。

如何导出这两个组件? - 请在同一问题上按照link进行操作。

答案 1 :(得分:0)

要解决此问题,您可以执行以下操作;

安装名为redux-mock-store npm install redux-mock-store

的库

像这样设置商店:

import configureStore from 'redux-mock-store';

const middlewares = [];
const mockStore = configureStore(middlewares);

添加您想要包含在商店中的任何中间件,例如。 redux-thunk,redux-sagas等。

定义您的初始状态,并按照以下步骤创建商店:

initialState = {}
const store = mockStore(initialState);

然后将新商店连接到您正在测试的组件:

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 ...

});