即使通过测试,在测试组件时也会出现错误

时间:2019-07-21 11:11:10

标签: javascript reactjs unit-testing automated-tests jestjs

我正在使用Jest和Enzyme编写我的React组件的单元测试用例。即使我所有的测试用例都通过了,我在此组件的测试中仍然收到错误。

我正在共享组件代码和下面出现的错误

echo '<input type="radio" name="' . strtolower($answer['answer']) . '">' . $answer['answer'];

下面是我正在为此组件运行的测试

class BidSummary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      techSpecMetric: [],
      isStateChanged: 1
    };
  }

  componentDidMount() {
    this.fetchTechSpec();
  }

  fetchTechSpec = async () => {
    this.setState({
      isLoading: true
    });
    const data = {
      quote_summary_id: get(this.props.match, 'params.bidId', '')
    };
    const techSpec = await this.props.fetchAssignedTechspec(data);
    if (isSuccess(techSpec)) {
      this.setState({
        techSpecMetric: (get(techSpec, 'payload.data', [])),
        isLoading: false
      });
    }
  }

  showmaterialIds = (cell, row) => {
    const content = row.Materials.map(item => (
      <li key={item.UPCProductConfigurationId}>
        <span className="materialName">{item.MaterialCode}</span>
        <span className="materialDescription">{item.MaterialName}</span>
      </li>
    ));

    return (
      <div>
        <Popover
          trigger="click"
          placement="bottomLeft"
          content={<ul className="materialIdsList">{content}</ul>}
          title={`Material IDs for ${row.TechSpecCode} (${row.Materials.length})`}
          overlayClassName="xyz"
        >
          <div
            style={{
              fontSize: '11px',
              textDecoration: 'underline',
              color: '#32C77F',
              display: 'inline-block'
            }}
          >
            {row.Materials.length}
          </div>
        </Popover>
      </div>
    );
  };

  /* This function calls when user click on Cancel link in the footer */
  onClickCancel = () => {
    this.props.history.push('/');
  }

  /* This function calls when user click on Back link in the footer */
  onClickBack = () => {
    this.saveAsDraftGroupData('back');
  }

  /* This function calls when user click on Cancel, Back or Save as draft link in the footer.
    It is used to save data.
  */
  saveAsDraftGroupData = async (type) => {
    const arrayWithGroups = [];
    forEach(this.state.techSpecMetric, (data) => {
      if (data.GroupName) {
        let sendingData = null;
        sendingData = {
          QuoteSummaryID: data.QuoteSummaryID,
          GroupName: data.GroupName
        };
        arrayWithGroups.push(sendingData);
      }
    });
    const quoteId = get(this.props.match, 'params.bidId', '');
    const response = await this.props.saveAssignedTechspec({ data: arrayWithGroups, is_draft: true, quote_summary_id: quoteId });
    isSuccess(response);
    if (type === 'back') {
      this.props.history.push(`/bid/${quoteId}/assign-techspec`);
    }
  }

  saveBidQuote = async () => {
    this.setState({
      isLoading: true
    });
    const data = {
      QuoteSummaryID: get(this.props.match, 'params.bidId', '')
    };
    const response = await this.props.updatePqrStatus(data);
    if (isSuccess(response)) {
      this.setState({
        isLoading: false
      });
      BcgSuccessNotification({
        message: response.payload.status,
        description: response.payload.message
      });
      this.props.history.push('/');
    } else {
      BcgSuccessNotification({
        message: response.payload.status,
        description: response.payload.message
      });
    }
  }

  fetchGroupsCount = (dataArray) => {
    const groupCount = uniq(dataArray.filter(data => data.GroupName));
    return groupCount.length;
  }

  techSpecCount = (dataArray, MG2) => {
    dataArray = dataArray.filter(data => data.MG2 === MG2);
    return dataArray.length;
  }

  render() {
    const techSpecs = sortBy(this.state.techSpecMetric, el => el.GroupName);
    return (
      <div key="quote-add-group-page" className="testss">
        {/* <QuoteHeader /> */}
        <Spinner spinning={this.state.isLoading}>
          <Row className="quote-add-product-page quote-summary-page">
            <Col span={24}>
              <Row>
                <QuotePageTitle
                  title={this.context.intl.formatMessage({ id: 'quote.bid.summary.page.heading' })} />
              </Row>
              <Row className="tech-specs-list-section">
                {
                  (
                    <BcgCollapse
                      className="data-table"
                      bordered={false}
                      expandIcon={({ isActive }) => <BcgIcon type="caret-right" theme="filled" rotate={isActive ? 90 : 0} />}
                    >
                      {
                        Object.entries(groupBy(techSpecs, 'MG2')).map(mg2Item => (
                          <BcgCollapse.Panel
                            header={<div className="collpase-title">{`${mg2Item[0]} (${this.fetchGroupsCount(mg2Item[1])})`}</div>}
                            key={mg2Item[0] + Math.random()}
                            className="grouped-mg2"
                          >
                            <Row className="mt-8 table-properties">
                              <BcgCollapse
                                className="data-table"
                                bordered={false}
                                expandIcon={({ isActive }) => <BcgIcon type="caret-right" theme="filled" rotate={isActive ? 90 : 0} />}
                              >
                                {
                                  Object.entries(groupBy((mg2Item[1]), 'GroupName')).map((groupItem, index) => {
                                    console.log('sorted array :::::::', sortBy(groupItem[1], el => el.GroupName));
                                    return ((groupItem[1].length > 0) && (mg2Item[1].length > 0 && mg2Item[1].some(el => (el.GroupName === groupItem[0] !== null && el.GroupName === groupItem[0])))
                                    ) ? (
                                      <BcgCollapse.Panel
                                        header={`${groupItem[0]} (${this.techSpecCount(groupItem[1], mg2Item[0])})`}
                                        key={index}
                                      >
                                        {
                                          <BcgTable
                                            loading={this.state.tableLoading}
                                            columns={this.state.columns}
                                            rowKey={record => (`${record.QuoteSummaryID}`)}
                                            size="middle"
                                            className="grouped-items-table"
                                            dataSource={groupItem[1]}
                                            pagination={false}
                                          />
                                        }
                                      </BcgCollapse.Panel>
                                    ) : (
                                      <div style={{ paddingRight: '20px' }}>
                                        <BcgTable
                                          loading={this.state.tableLoading}
                                          columns={this.state.columns}
                                          rowKey={record => (`${record.QuoteSummaryID}`)}
                                          size="middle"
                                          dataSource={groupItem[1]}
                                          pagination={false}
                                        />
                                      </div>
                                    );
                                  })
                                }
                              </BcgCollapse>
                            </Row>
                          </BcgCollapse.Panel>
                        ))
                      }
                    </BcgCollapse>
                  )
                }
              </Row>
            </Col>
          </Row>
        </Spinner>
        <QuoteFooter
          isStateChanged={this.state.isStateChanged}
          onClickCancel={this.onClickCancel}
          onClickBack={this.onClickBack}
          actionProps={{
            onProceed: this.saveBidQuote,
            onSaveAsDraft: this.saveAsDraftGroupData
          }}
          showBack />
      </div>
    );
  }
}

/**
 * @readonly
 */

BidSummary.propTypes = {
  match: PropTypes.object,
  saveAssignedTechspec: PropTypes.func,
  fetchAssignedTechspec: PropTypes.func,
  history: typeOfObject,
  getQuoteStatus: PropTypes.func,
  updatePqrStatus: PropTypes.func
};
/**
 * @readonly
 */
BidSummary.contextTypes = {
  intl: PropTypes.object
};


function mapDispatchToProps(dispatch) {
  return {
    fetchAssignedTechspec: data => dispatch(fetchAssignedTechspec(data)),
    saveAssignedTechspec: data => dispatch(saveAssignedTechspec(data)),
    updatePqrStatus: data => dispatch(updatePqrStatus(data))
  };
}

export {BidSummary};
export default connect('', mapDispatchToProps)(withRouter(BidSummary));

现在这些测试通过了,但是我也收到下面提到的错误

describe('BidSummary', () => {
  const match = {
    params: {
      bidId: 'asdasdd'
    }
  };

  it('should render correctly', () => {
    const wrapper = shallowWithIntl(<BidSummary match={match} history={undefined}/>);
    expect(wrapper).toMatchSnapshot();
  });

  it('should contains a class', () => {
    const wrapper = shallowWithIntl(<BidSummary match={match} history={undefined}/>);
    expect(wrapper.exists('.quote-summary-page')).toEqual(true);
  });

  it('should contains a spinner', () => {
    const wrapper = shallowWithIntl(<BidSummary match={match} history={undefined}/>);
    expect(wrapper.exists(Spinner)).toEqual(true);
  });
  it('should contains Collapse component', () => {
    const wrapper = shallowWithIntl(<BidSummary match={match} history={undefined}/>);
    expect(wrapper.find(BcgCollapse)).toHaveLength(1);
  });

  it('should fetch data from api', () => {
    const getData = {
      quote_summary_id: ''
    };
    let fetchAssignedTechspec = jest.fn();
    const wrapper = shallowWithIntl(<BidSummary fetchAssignedTechspec={fetchAssignedTechspec} />);
    expect(wrapper).toBeDefined();
    expect(fetchAssignedTechspec).toHaveBeenCalled();
    expect(fetchAssignedTechspec.mock.calls[0]).toEqual([getData]);
  });

  it('should fetch data from api', () => {
    const getData = {
      quote_summary_id: ''
    };
    let fetchAssignedTechspec = jest.fn();
    const wrapper = shallowWithIntl(<BidSummary fetchAssignedTechspec={fetchAssignedTechspec} />);
    expect(wrapper).toBeDefined();
    expect(fetchAssignedTechspec).toHaveBeenCalled();
    expect(fetchAssignedTechspec.mock.calls[0]).toEqual([getData]);
  });
});

我想知道我在哪里做错了以及如何正确编写测试用例,这样我就不会出现此错误?

请让我知道谢谢。

0 个答案:

没有答案