测试redux连接组件

时间:2017-08-10 22:05:33

标签: unit-testing redux sinon enzyme jest

我在React-Redux中有以下连接组件

export class IncrementalSearch extends React.Component {

    constructor(props) {
        super(props);
        this.onSearch$ = new Subject();
        this.onChange = this.onChange.bind(this);
    }

    componentDidMount() {
        this.subscription = this.onSearch$
            .debounceTime(300)
            .subscribe(debounced => {
                this.props.onPerformIncrementalSearch(debounced);
            });
    }

    componentWillUnmount() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }

    onChange(e) {
        const newText = e.target.value;
        this.onSearch$.next(newText);
    }

    render() {
        return (
            <div className={styles.srchBoxContaner}>
                <input
                    className={styles.incSrchTextBox}
                    type="text" name="search" id="searchInput" placeholder="Search.."
                    onChange={this.onChange}
                />
            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    onPerformIncrementalSearch: (searchText) => {
        dispatch(performIncrementalStoreSearch(searchText));
    }
});

const IncrementalSearchComponent = connect(null, mapDispatchToProps)(IncrementalSearch);
export default IncrementalSearchComponent;

我现在正在尝试为连接的组件编写单元测试。我使用的是Jest,Enzyme和Sinon。到目前为止,这是我的单元测试的样子

it('calls \'onPerformIncrementalSearch\' when the user types in something', () => {
    const mockStore = configureStore();

    const onPerformIncrementalSearchSpy = sinon.spy();
    const mapStateToProps = null;
    const mapDispatchToProps = {
        onPerformIncrementalSearch: onPerformIncrementalSearchSpy
    };

    const mappedProps = { mapStateToProps, mapDispatchToProps };

    const incrementalSearchWrapper =
        mount(
            <Provider store={mockStore}>
                <IncrementalSearchComponent
                    onPerformIncrementalSearch={onPerformIncrementalSearchSpy}
                    props={mappedProps}
                    store={mockStore}
                />
            </Provider>
        );


    //find the input element
    const searchInput = incrementalSearchWrapper.find('#searchInput');
    searchInput.node.value = 'David';
    searchInput.simulate('change', searchInput);
    expect(onPerformIncrementalSearchSpy.called).toEqual(true);
    // onChangeSpy.restore();
});

但是,当我运行此测试时,我收到以下错误

  

TypeError:无法读取属性&#39; bind&#39;未定义的

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

测试连接的组件可能是一个巨大的痛苦。我发现尝试使用Provider包装您的组件以让他们访问商店更加麻烦。

相反,我只想导出组件mapStateToPropsmapDispatchToProps并单独测试它们。如果您将连接的组件导出为默认值,您的应用仍然可以正常工作。

Dan Abramov(Redux的共同作者)在this comment

中提出了这种方法

我还建议在测试连接的组件时调查enzyme shallow rendering而不是使用mount