簡體   English   中英

如何使用Jest和Enzyme為簡單的React組件編寫測試用例

[英]How to write a test case for a simple React component using Jest and 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>
 )
}

因此,如果我想使用JestEnzyme為上述組件編寫一個測試用例,可以為該組件編寫的可能的測試用例是什么? 有人可以指導我嗎? 我無法找出可能的測試用例,因為我在此組件中沒有任何功能,因此我可以在Expect()函數中檢查該函數的結果。

我相信不要為該簡單組件編寫任何單元測試,而將您的短時間集中在編寫這樣的端到端測試上是可以的。

如果您的經理正在監視應用程序中測試的百分比覆蓋率,則只需測試您的組件是否呈現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');

就在我最近進入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>
      );
    });
  });
});

將來,您至少應在尋求幫助之前嘗試解決方案。 如果他們看到您自己做出了一些努力,那么這里的社區將給他們更多的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM