如何使用组件方法测试状态更改

时间:2019-04-11 14:03:11

标签: reactjs jestjs enzyme

我正在测试组件,需要测试其更新状态的方法。这些方法会更新状态,而在测试这些状态更改时遇到了一些麻烦。

我的测试如下:

  it('componentDidMount() test', () => {
    const loancont = shallow(<LoanFilesContainer store={store} searchText='testing' firstUpdate={false} uploadingExcel={true}/>)
    const prewrap = mount(loancont.get(0))
    const loancontwrap = prewrap.find('LoanFilesContainer')
    const wrapper = mount(loancontwrap.get(0))
    expect(wrapper.state('firstUpdate')).toEqual(false)
    wrapper.instance().state.uploadingExcel = true
    wrapper.instance().componentWillUpdate()
    wrapper.update()
    expect(wrapper.state('firstUpdate')).toEqual(true)
  })

我的代码如下:

class LoanFilesContainer extends Component {
    state = {
      searchText: '',
      isBulkCreating: false,
      loansToConvert: [],
      uploadingExcel: false,
      firstUpdate: false
    }

    componentDidMount() {
      this.props.fees.filter({ limit: 0 })
    }

    componentWillUpdate() {
      const { uploadingExcel, firstUpdate } = this.state
      if(uploadingExcel && !firstUpdate) { this.setState({ firstUpdate: true }) }
      if(uploadingExcel && firstUpdate) { this.setState({ uploadingExcel: false, firstUpdate: false }) }
    }

    render() {
      const { ...props } = this.props
      const {
        searchText,
        isBulkCreating,
        loansToConvert,
        uploadingExcel
      } = this.state

      return (
        <main className="main">
          {props.loans.data && (
            <LoanFiles
              data-test="input"
              {...props}
              handleCSV={this.handleCSV}
              searchText={searchText}
              onFieldChange={this.onFieldChange}
              onSearchSubmit={this.onSearchSubmit}
              onOrderAll={this.onOrderAll}
              uploadRef={this.uploadRef}
            />
          )}
          {(props.loans.isLoading || !props.loans.data || props.orderAdd.isLoading || props.upload1003.isLoading) && <Loader/>}
          {isBulkCreating ? <BulkLoader title='Creating Orders In Bulk...' /> : null}
          {uploadingExcel && <BulkLoader title='Uploading Loan Data...' />}
          {!isBulkCreating && loansToConvert.length > 0 ? <ChainedCreateOrderModal loans={
            loansToConvert
          } onFinish={this.onChainedOrderCreationFinish} /> : null}
        </main>
      )
    }
}

基于if语句,检查firstupExcel和firstUpdate的状态,firstUpdate状态应更改为true。但是即使更新后它仍返回false。

0 个答案:

没有答案