Javascript 如何在React Router 4下对组件进行单元测试

Javascript 如何在React Router 4下对组件进行单元测试,javascript,reactjs,react-router,mocha.js,enzyme,Javascript,Reactjs,React Router,Mocha.js,Enzyme,我有一个要测试其行为的组件: import React from 'react'; import {connect} from 'react-redux'; import {getModules, setModulesFetching} from 'js/actions/modules'; import {setModuleSort} from 'js/actions/sort'; import Loading from 'js/Components/Loading/Loading'; im

我有一个要测试其行为的组件:

import React from 'react';
import {connect} from 'react-redux';

import {getModules, setModulesFetching} from 'js/actions/modules';
import {setModuleSort} from 'js/actions/sort';

import Loading from 'js/Components/Loading/Loading';
import Module from './Components/ModuleListModule';

export class ModulesList extends React.Component {
    componentDidMount() {
        this.props.setModulesFetching(true);
        this.props.getModules();
    }

    renderModuleList() {
        if (this.props.isFetching) {
            return <Loading/>;
        }

        if (this._isSelected('name')) {
            this.props.modules.sort((a, b) => this._compareNames(a, b));
        } else if (this._isSelected('rating')) {
            this.props.modules.sort((a, b) => this._compareRatings(a, b));
        }

        return this.props.modules.map((module) =>
            <Module key={module.id} module={module}/>
        );
    }

    renderSelect() {
        return (
            <div className="col">
                <label htmlFor="search-sortby">Sort By:</label>
                <select id="search-sortby" onChange={(event) => this.props.setModuleSort(event.target.value)}>
                    <option value="name" selected={this._isSelected('name')}>Name</option>
                    <option value="rating" selected={this._isSelected('rating')}>Rating</option>
                </select>
            </div>
        );
    }

    render() {
        return (
            <div id="modules-list">
                <div className="p-3 row">
                    {this.renderSelect()}
                    <div id="search-summary">
                        {this.props.modules.length} Adventures Found
                    </div>
                </div>

                {this.renderModuleList()}
            </div>
        );
    }
// Other minor methods left out for brevity
}
如何设置测试,以便调用
setProps()
,组件实际更新


为此工作了几天,并提出了解决方案。我开始模拟Redux商店,但其余的我都是通过谷歌搜索拼凑起来的

/* global describe, it */
import {MemoryRouter} from 'react-router-dom';
import {ModulesList} from 'js/Scenes/Home/ModulesList';
import {Provider} from 'react-redux';
import React from 'react';
import {assert} from 'chai';
import configureStore from 'redux-mock-store';
import {shallow} from 'enzyme';
import sinon from 'sinon';

describe('ModulesList' () => {
    it('should sort by name, when requested.', () => {
        const storeFactory = configureStore([]);
        const store = storeFactory({});
        # This is the harness my component needs in order to function in the
        # test environment.
        const TestModulesList = (props) => {
            return (
                <Provider store={store}>
                    <MemoryRouter>
                        <ModulesList {...props}/>
                    </MemoryRouter>
                </Provider>
            );
        };

        const initialProps = {
            getModules: sinon.stub(),
            isFetching: false,
            modules: [],
            setModulesFetching: sinon.stub(),
            sortBy: 'name'
        };

        const wrapper = shallow(<TestModulesList {...initialProps}/>);
        const nextModules = [/* omitted */];
        wrapper.setProps({modules: nextModules});

        assert.equal(wrapper.render().find('#search-summary').text(), '2 Adventures Found');
    });
});
/*全局描述,它*/
从'react router dom'导入{MemoryRouter};
从“js/Scenes/Home/ModulesList”导入{ModulesList};
从'react redux'导入{Provider};
从“React”导入React;
从'chai'导入{assert};
从“redux模拟存储”导入configureStore;
从“酶”导入{shall};
从“sinon”进口sinon;
描述('ModulesList'()=>{
它('应在请求时按名称排序',()=>{
const storeFactory=configureStore([]);
const store=storeFactory({});
#这是我的部件需要的线束,以便在
#测试环境。
常量TestModulesList=(道具)=>{
返回(
);
};
常量initialProps={
getModules:sinon.stub(),
isFetching:false,
模块:[],
setModulesFetching:sinon.stub(),
下流的:“名字”
};
常量包装器=浅();
常量nextModules=[/*省略*/];
setProps({modules:nextModules});
assert.equal(wrapper.render().find(“#搜索摘要”).text(),“发现2次冒险”);
});
});
import {MemoryRouter} from 'react-router-dom';
import {ModulesList} from 'js/Scenes/Home/ModulesList';
import React from 'react';
import {assert} from 'chai';
import {shallow} from 'enzyme';
import sinon from 'sinon';

describe('ModulesList', () => {
    it('should sort by name, when requested.', () => {
        const initialProps = {
            getModules: sinon.stub(),
            isFetching: false,
            modules: [],
            setModulesFetching: sinon.stub(),
            sortBy: 'name'
        };

        const wrapper = shallow(
            <MemoryRouter>
                <ModulesList {...initialProps}/>
            </MemoryRouter>
        );
        const nextModules = [
            {
                avg_rating: [{
                    aggregate: 1.0
                }],
                edition: {
                    name: "fakeedition"
                },
                id: 0,
                name: "Z module"
            },
            {
                avg_rating: [{
                    aggregate: 1.0
                }],
                edition: {
                    name: "fakeedition"
                },
                id: 1,
                name: "Y module"
            }
        ];

        wrapper.setProps({modules: nextModules});
        assert.equal(wrapper.render().find('#search-summary').text(), '3 Adventures Found');
    });
});
Warning: Failed context type: The context `router` is marked as required in `Link`, but its value is `undefined`.
in Link (created by ModuleListModule)
in ModuleListModule
in div

TypeError: Cannot read property 'history' of undefined
/* global describe, it */
import {MemoryRouter} from 'react-router-dom';
import {ModulesList} from 'js/Scenes/Home/ModulesList';
import {Provider} from 'react-redux';
import React from 'react';
import {assert} from 'chai';
import configureStore from 'redux-mock-store';
import {shallow} from 'enzyme';
import sinon from 'sinon';

describe('ModulesList' () => {
    it('should sort by name, when requested.', () => {
        const storeFactory = configureStore([]);
        const store = storeFactory({});
        # This is the harness my component needs in order to function in the
        # test environment.
        const TestModulesList = (props) => {
            return (
                <Provider store={store}>
                    <MemoryRouter>
                        <ModulesList {...props}/>
                    </MemoryRouter>
                </Provider>
            );
        };

        const initialProps = {
            getModules: sinon.stub(),
            isFetching: false,
            modules: [],
            setModulesFetching: sinon.stub(),
            sortBy: 'name'
        };

        const wrapper = shallow(<TestModulesList {...initialProps}/>);
        const nextModules = [/* omitted */];
        wrapper.setProps({modules: nextModules});

        assert.equal(wrapper.render().find('#search-summary').text(), '2 Adventures Found');
    });
});