2

Suppose I have the following component:

const MyComponent = () => null;

In React Testing Library (RTL), the following, AFAIK, should work:

const { container } = render(<MyComponent />);

expect(container.firstChild).toBeEmpty();

where .toBeEmpty is a custom matcher from jest-dom. However, in NTL, container.firstChild is not defined so I can't use .toBeEmpty matcher from jest-native. After some experimentation, I got it to work as follows:

expect(container.children[0]).toBeUndefined();

Is there any other, possibly better, way to do this?

1 Answers1

0

In my case I had a situation like so:

function PhotoComponent({policy}) {
  if (policy === 'unavailable')
    return null;
  
  return (<View />);
}

Tested like this:

it("should not render if policy is 'unavailable'", () => {
  const {toJSON} = render(<PhotoComponent policy={'unavailable'} />);
  const children = toJSON().children;
  expect(children.length).toBe(0);
});

Some times you will want to filter the children like, for instance:

const children = toJSON().children.filter(
  (child) => child.type === 'View' || child.type === 'Modal'
);

Keep calm and Happy coding!

sugaith
  • 772
  • 7
  • 14