Skip to content
Advertisement

Jest tests keep failing for React component that renders various HTML elements based on type by using switch statement

I have a React Component that takes an array and iterates over each node, styling and rendering HTML elements based on the types found within the array.

I have everything running properly and now I’m trying to write a test using Jest to check that:

  1. The component doesn’t render anything when it receives an empty array
  2. The component renders the appropriate HTML elements based on type when it receives a populated array

I’m relatively new to Jest and testing and I’m not sure how to write the tests to check that the appropriate elements have rendered. Also my null check test keeps failing with the following error message:

JavaScript

This is my testing file:

JavaScript

And this is my original component that I’m testing:

JavaScript

Advertisement

Answer

When you return null from component, React.createElement still creates an element. And there is no way to actually tell if it will render nothing without inspecting resulted markup.

For example this code will give you proper react element in console, not null:

JavaScript

You can try to render your components into jsdom and check snapshots or expected markup (or both)

Edit: Instead of jsdom it is possible to render to string. In this case you should get empty string

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement