单元测试:如何测试redux“Provider”?

时间:2018-03-09 05:35:36

标签: reactjs unit-testing redux

我有一个像下面这样的函数,这是一个提供EstateList的rudux。

import {render} from "react-dom";
import React from "react";
import {Provider} from "react-redux";
import store from "./Store";
import EstateList from "../estates/estateList/estateList";

function estateList() {
    render(
        <Provider store={store}>
            <EstateList />
        </Provider>,
        window.document.getElementById('estateList')

    );
}

和EstateList是这样的:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {connect} from "react-redux";

class EstateList extends Component {
    constructor(){
      ...
      console.log('this can not be seen');
    }
    render() {...}
}

const mapStateToProps = (state) => {
    return {
        title: state.subNavReducer.title
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        setSubNav: (title) => {            
            dispatch({
                type: "SET_TITLE",
                payload: title
            });
        }
    };
};

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

我尝试测试EstateList,如下所示:

import {shallow, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import {expect} from 'chai';

import {Provider} from "react-redux";
import store from "../../../components/store/Store";
import EstateList from "../../../components/estates/estateList/estateList";
//import {EstateList} from "../../../components/estates/estateList/estateList";

describe('estate', function () {
    it('getArticlesFromDatabase ', function () {
        let app = shallow(
            <Provider store={store}>
                <EstateList />
            </Provider>
        );
    });
});

但是它显示了这条警告信息:

  

console.error node_modules / fbjs / lib / warning.js:33       警告:React.createElement:type无效 - 期望字符串(对于内置组件)或类/函数(对于组合)   组件)但得到:未定义。你可能忘了导出你的   来自其定义的文件中的组件。

如何解决?

我改变了

从“../../../ components / estates / estateList / estateList”导入 {EstateList} ;

从“../../../ components / estates / estateList / estateList”导入 EstateList ;

然后警告消息消失。

但似乎类 estateList 仍然没有被破坏。 因为当我运行测试时,我没有看到我在estateList的构造函数中添加的 console.log

顺便说一句,如果我改变了

it('getArticlesFromDatabase ', function () {
    let app = shallow(
        <Provider store={store}>
            <EstateList />
        </Provider>
    );
});

it('getArticlesFromDatabase ', function () {
    let app = shallow(
        <Provider store={store}>
            <EstateList />
        </Provider>
    ).dive();
});

然后我会收到以下错误消息:

  

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

1 个答案:

答案 0 :(得分:0)

你不应该为提供者编写测试,图书馆的作者已经为你做过。

您正在导入您的EstateList组件错误,您导出默认值,然后正在为命名导入执行对象结构导入。

只是import EstateList from 'path'