简体   繁体   中英

Testing a component with two pure components

I have a component that renders a image banner. This component makes use of data to specifically render the image banner on mobile or desktop.

I have two pure function components to handle the case for mobile and desktop.

Here is a sample of what it looks like

<ImageBanner>
   {mobile?.image && <MobileBanner mobile={mobile} />}
   {desktop?.image && <DesktopBanner desktop={desktop} />}
</ImageBanner>

MobileBanner and DesktopBanner are pure functional components that just return back html. I want to write jest test for the above component, how do I write a test for the component ImageBanner ?

There is really straightforward approach: 1. if mobile.image exists - <MobileBanner> is rendered with mobile={mobile} passed

it("renders MobileBanner is mobile passed`, () => {
  const mobile = {image: 'test'};
  const root = shallow(<YourComponent mobile={mobile} />);
  expect(root.find(MobileBanner).prop().mobile).toEqual(mobile);
  expect(root.find(DesktopBanner)).toHaveLength(0);
});
  1. if desktop.image exists - <DesktopBanner is rendered with desktop={desktop} passed
it("renders DesktopBanner is mobile passed`, () => {
  const desktop = {image: 'test'};
  const root = shallow(<YourComponent desktop={desktop} />);
  expect(root.find(DesktopBanner).prop().desktop).toEqual(desktop);
  expect(root.find(MobileBanner)).toHaveLength(0);
});

  1. even if both mobile and desktop are undefined - there is no error(at least <ImageBanner> is rendered)
it("does not fail if neither mobile nor desktop prop passed", () => {
  const root = shallow(<YourComponent />);
  expect(root.find(MobileBanner)).toHaveLength(0);
  expect(root.find(DesktopBanner)).toHaveLength(0);
  expect(root.find(ImageBanner).exists()).toBeTruthy();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM