Testing Components Guidelines

1. Introduction

In here its explain some guidelines about how we should test a React Component. If you have time, read the original post, this is an extract of it.

2. Component Contract

A contract defines the expected behavior of your component and what assumptions are reasonable to have about its usage. Without a clear contract, your component may be hard to understand. Writing tests is a great way to formally define your component’s contract.

Every React component has at least one thing that contributes to the definition of its contract:

  • What it renders(which may be nothing, like some high order components)

Additionally, most component contracts are affected by these things as well:

  • The props the component receives
  • The state the component holds (if any)
  • What the component does when the user interacts with it (via clicking, dragging, keyboard input, etc)

Some less common things that affect component contracts are:

  • The context the component is rendered in
  • What the component does when you call methods on its instance (public ref interface)
  • Side effects that occur as part of the component lifecycle (componentDidMount, componentWillUnmount, etc)

To find your component’s contract, ask yourself questions like:

  • What does my component render?
  • Does my component render different things under different circumstances?
  • When I pass a function as a prop, what does my component use it for?Does it call it, or just give it to another component? If it calls it, what does it call it with?
  • When the user interacts with my component, what happens?

3. What is worth testing?

Here are three rules of thumb I use to determine that something is not worth testing:

  1. Will the test have to duplicate exactly the application code? This will make it brittle.
  2. Will making assertions in the test duplicate any behavior that is already covered by (and the responsibility of) library code?
  3. From an outsider’s perspective, is this detail important, or is it only an internal concern? Can the effect of this internal detail be described using only the component’s public API?

4. Interesting Articles about testing

  1. Testing React Components Best Practices(Folder structure, how to create readable test, helper functions, etc)
  2. Testing React Applications with Jest(Step by step guide of how to test a component with React, coverage reporting, etc)
  3. The right Way to Test React Components(Component contract, excellent example of what is worth testing in a component)

5. References

  1. The right Way to Test React Components

results matching ""

    No results matching ""