当前位置:  开发笔记 > 编程语言 > 正文

如何为调用reduxjs的mapStateToProps的react组件编写单元测试?

如何解决《如何为调用reduxjs的mapStateToProps的react组件编写单元测试?》经验,为你挑选了1个好方法。

我正在尝试为被调用的容器组件编写单元测试,AsyncApp但是我得到以下错误" mapStateToProps必须返回一个对象.而是收到未定义的."

这是我的设置.

Root.js

import configureStore from '../configureStore';
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import AsyncApp from './AsyncApp';

const store = configureStore();

export default class Root extends Component {
  render() {
    return (
      
        
      
    );
  }
}

configureStore.js

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from './reducers';

const loggerMiddleware = createLogger();

const createStoreWithMiddleware = applyMiddleware(
  thunkMiddleware
  //loggerMiddleware
)(createStore);

export default function configureStore(initialState) {
  return createStoreWithMiddleware(rootReducer, initialState);
}

AsyncApp.js

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { foo } from '../actions';
import FooComponent from '../components/FooComponent';

class AsyncApp extends Component {
  constructor(props) {
    super(props);
    this.onFoo= this.onFoo.bind(this);
    this.state = {}; // <--- adding this doesn't fix the issue
  }

  onFoo(count) {
    this.props.dispatch(foo(count));
  }

  render () {
    const {total} = this.props;

    return (
      
); } } function mapStateToProps(state) { return state; } export default connect(mapStateToProps)(AsyncApp);

store直接通过AsyncApp我的测试,以避免出现以下运行时错误:Could not find "store" in either the context or props of "Connect(AsyncApp)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(AsyncApp)".

测试尚未完成,因为我无法通过mapStateToProps错误消息.

AsyncApp-test.js

jest.dontMock('../../containers/AsyncApp');
jest.dontMock('redux');
jest.dontMock('react-redux');
jest.dontMock('redux-thunk');
jest.dontMock('../../configureStore');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
const configureStore = require( '../../configureStore');
const AsyncApp = require('../../containers/AsyncApp');

const store = configureStore();

//const asyncApp = TestUtils.renderIntoDocument(
  //
//);

const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render();

我想最终测试AsyncApp包含a FooComponent,并fooonFoo调用时调度一个动作.

我想要做到的是可以实现的吗?我是以正确的方式来做这件事的吗?



1> markerikson..:

我在几个地方看到的建议是测试非连接组件,而不是连接版本.因此,验证当您将特定道具传递给组件时,您将获得预期的渲染输出,并验证当您传入具有特定形状的状态时,您mapStateToProps()将返回预期的碎片.那么你可以期待它们在放在一起时都能正常工作.


您可能最终会遇到测试未连接组件的情况......但在一个相当复杂的应用程序中,可以连接该非连接组件的子项.所以它并不总是那么简单(除非只连接你的顶层组件).除了模仿进口之外,还没有找到一个好的解决方案.
推荐阅读
雯颜哥_135
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有