The Right Way to Test React Components
Stephen Scott
3.7K22

Thank you, this certainly has helped me to choose which parts of my components to test. I’d like to ask a couple of questions about it.

Question #1

How is `describe(“when onUnlocked is defined”)… it(“sets the rendered SlideToUnlock’s onSlide prop to the same value as onUnlocked’”) different to describe(“when onUnlocked is undefined”)… it(“sets the rendered SlideToUnlock’s onSlide prop to undefined’”), and how does that difference necessitates the second assertion?

I’m sorry, I was unable to see the need to do so. However, in cases where the absence of the prop is expected to cause other things (like hiding the component that would’ve received the prop), I see the need to test it.

Question #2

I’ve originally asked this stackoverflow. Honestly, it doesn’t directly relate to you examples but it has to something to do with deciding which component should test which.

Let’s say we have this to do app:

// TodoContainer.jsx
<TodoContainer>
<AddTodo />
<TodoList />
</TodoContainer>

My question is how should I test its add todo functionality? Is it enough to..

Approach #1

  1. Shallow render TodoContainerand assert that..
    a. it has a working addTodoMethodwhich updates the state accordingly
    b. it passes the addTodoMethodits child composite component, addTodo
  2. Shallow render AddTodoand assert that..
    a. it has received the addTodoMethodas prop
    b. it fires the addTodoMethodon button click

Approach #2

  1. in addition to assertions above, also mount the TodoContainer to assert that..
    a. it can add a todo item thru inputting new to do text and clicking button (both in AddTodocomponent), the new todo item is also asserted thru transversing to TodoList component and check if it has the correct number of li with their correct content.

I’m just thinking if the second approach is kinda redundant (alright, it is the lazy part of me who’s thinking it), and if it is a better practice to focus only on testing the component at hand and letting the child components rely on their own tests.

BTW, I’ve provided code example for both approaches above in stackoverflow.

Thanks!