如何在reactjs应用程序中用酶找到元素?

时间:2019-05-03 09:42:32

标签: javascript reactjs unit-testing enzyme

在我的react应用程序中,我有一个带有几个选择的Container组件:

import React, { Component } from "react";
import DebtType from "./DebtType";
import mockOptions from "./mockData.json";
import ClearDebtType from "./ClearDebt";
import { reduxForm, formValueSelector, Field } from "redux-form";
import { connect } from "react-redux";

 export class MyContainer extends Component {
  handleChangeDebtType = event => {
    console.log("handleChangeDebtType value", event.target.value);
    this.props.change("debtType", event.target.value);
    if (event.target.value === "4" || event.target.value === "5") {
      this.props.change("newLimit", 0);
    }
    if (
      event.target.value === "0" ||
      event.target.value === "3" ||
      event.target.value === "7"
    ) {
      this.props.change("newLimit", this.props.currentLimit);
    }

    if (
      event.target.value === "1" ||
      event.target.value === "2" ||
      event.target.value === "6"
    ) {
      this.props.change("newLimit", "");
    }
  };

  render() {
  const { debtType, newLimit } = this.props;

    return (
      <div>
        <DebtType
          options={mockOptions.DEBT_TYPE}
          handleChangeDebtType={this.handleChangeDebtType}
        />

        {(debtType === "1" || debtType === "2") && (
          <ClearDebtType options={mockOptions.CLEARDEBT_TYPE} />
        )}


      </div>
    );
  }
}

这些是select组件:

import React from "react";

const ClearDebt = ( options) => {
console.log(options)
  return (
    <select>
      {options.options.map(option => {
        return <option>{option.label}</option>;
      })}
    </select>
  );
};

export default ClearDebt;

import React from "react";

const DebtType = ({options, handleChangeDebtType}) => {
  console.log(options);

  return (
    <select onChange={handleChangeDebtType}>
      {options.map(option => {
        return <option value={option.value}>{option.label}</option>;
      })}
    </select>
  );
};

export default DebtType;

在开玩笑的单元测试中,我想测试第二个选择的可见性(取决于第一个选择的选择值):

describe('Container component', () => {
    it('should show the second select component', () => {
        const myComp = shallow(<MyContainer debtType={"1"}/>);
        //question: how can I find the second select in the browser?
        //https://airbnb.io/enzyme/docs/api/ReactWrapper/find.html
        const result = myComp.find('#root > div > div > select:nth-child(2)')   
        console.log('result',result.length)
        expect(result.length ).toEqual(1)
    });
  });

问题是我无法通过以下语句找到元素:

 const result = myComp.find('#root > div > div > select:nth-child(2)')  

这是测试的结果:

 Container component › should show the second select component

    expect(received).toEqual(expected)

    Expected: 1
    Received: 0

如何选择第二个列表框? 顺便说一句,我愿意接受其他测试框架。

1 个答案:

答案 0 :(得分:-1)

尝试

canBus.send()