2017-08-10 69 views
0

我在阵营 - 终极版测试终极版连接组件

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(); 
}); 

然而,当我运行这个测试,我得到以下错误

类型错误:无法读取的不确定

财产“绑定”我该如何解决这个?

回答

3

测试连接组件可能是一个巨大的痛苦。我发现它比尝试用Provider包装你的组件来让他们进入商店更加麻烦。

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

丹·阿布拉莫夫(共终极版的作者)建议在this comment

这种方法我也建议寻找到enzyme shallow rendering,而不是测试连接部件在使用mount

+0

但是,连接的组件不仅仅是mapStateTrops和mapDispatchToProps,组件中还有其他逻辑需要测试。那么我该如何测试呢? –

+0

您仍然可以通过这种方法测试组件中的逻辑。你只需要两个“出口”。一种方法是导出连接组件'export default connect ...',然后通过'import {default as myComponent}'将其导入到应用程序中。您还可以导出未连接的组件,如'export class myComponent',并在您的测试中导入,例如'import {myComponent}'。然后,您可以测试组件中的所有逻辑,而无需担心访问存储和测试连接的组件。 – bill

+0

[此答案](https://stackoverflow.com/a/35578985/6326906)可能有助于进一步解释。 – bill