如何使用Jest和Enzyme为简单的React组件编写测试用例

时间:2018-05-08 09:03:43

标签: javascript reactjs jestjs enzyme

我有一个简单的React组件,看起来如下所示:

export default class New_Component {
   static propTypes = {
        name: PropTypes.string.isRequired,
        mobile: PropTypes.number.isRequired,
        address: PropTypes.string.isRequired
   };
}

render() {
   return(
    <div>
      <h1>{this.props.name}</h1>
      <h6>{this.props.mobile}</h6>
      <p>{this.props.address}</p>
   </div>
 )
}

因此,如果我想使用 Jest Enzyme 为上述组件编写测试用例,那么可以为该组件编写哪些可能的测试用例?有人可以指导我吗?我无法弄清楚可能的测试用例是什么,因为我在这个组件中没有任何函数,因此我可以在 expect()函数中检查函数的结果。

2 个答案:

答案 0 :(得分:1)

我相信可以不为该简单组件编写任何单元测试,并将您的短时间集中在地球上,例如编写端到端测试。

如果您的经理正在监控您应用中测试的%覆盖率,则只需测试您的组件呈现namemobileaddress

const wrapper = shallow(<New_Component
  name="testName"
  mobile="000000"
  address="addressMobile"
/>);

expect(wrapper.find('h1').text()).to.equal('testName');
expect(wrapper.find('h6').text()).to.equal('000000');
expect(wrapper.find('p').text()).to.equal('addressMobile');

答案 1 :(得分:1)

由于我刚刚进入React世界,我会给你一个开始的样本。测试可能是一项艰巨的任务。

但是,我同意接受的答案,因为对于这样大小的组件来说这可能是过度的。

这可能是我可能变得更加复杂的起点。

describe("<New_Component/>", () => {
  let actual;

  const complete_props = {
    name: "test",
    mobile: 12345678,
    address: "123 test road"
  };



 describe("given all neccessary props", () => {
    beforeEach(() => {
      actual = shallow(<NewComponent {...complete_props} />);
    });

    it("renders correctly", () => {
      expect(actual).toMatchSnapshot();
    });

    it("should render the component", () => {
      expect(actual.find("NewComponent"));
    });

    it("should render three children", () => {
      expect(actual.children().length).toEqual(3);
    });

    it("should render h1 with correct prop", () => {
      expect(actual.props().children[0]).toEqual(
        <h1>{complete_props.name}</h1>
      );
    });

    it("should render h6 with correct prop", () => {
      expect(actual.props().children[1]).toEqual(
        <h6>{complete_props.mobile}</h6>
      );
    });

    it("should render p with correct prop", () => {
      expect(actual.props().children[2]).toEqual(
        <p>{complete_props.address}</p>
      );
    });
  });
});

将来您应该在寻求帮助之前至少尝试解决方案。如果他们看到你自己做了一些努力,那么这里的社区就更愿意花时间。

相关问题