React ~ Testing ~ Component - rohit120582sharma/Documentation GitHub Wiki

Testing Strategies

Snapshot testing

It allows you to save a HTML DOM snapshot of the React component in the first run. All the subsequent test runs will be comparing the subsequent snapshots with this first snapshot to determine whether there has been any DOM (UI) changes in the component.


Testing props

Firstly, check proptypes to test what type of data comes in the props using check-prop-types library

Secondly, check the render/behavior of default prop values.

Finally, check the custom value of the prop. I set my own value and expect it to be received after the rendering of the component.


Testing state

To check state, in most cases, it is necessary to write two tests:

  • The first one checks the current state
  • The second one checks the state after calling an event. Render component => call function directly in the test => check how state has changed.

Rendering

You can check rendering for following:

  • Check for some components with expected props
  • Check props.children

Event testing

You can check event in several ways. The most widely used are:

  • mock event => simulate it => expect event was called
  • mock event => simulate event with params => expect event was called with passed params
  • pass necessary props => render component => simulate event => expect a certain behaviour on called event

Testing conditions

Very often you can have conditions for the output of a particular class, rendering a certain section of the code, transferring the required props, and so on.



Connected Component Testing

The conventional wisdom of testing components that use Redux is that you should test the component in isolation from Redux, and then test the Redux action creators and reducers separately.

But if you do this, your tests can’t give you any confidence that your components communicate properly with Redux.

Instead, you can actually test your connected component with your real Redux store. Do this, and you’ll get the confidence that your component is rendering properly, and that the Redux action creators and reducers are all working together in tandem. Just like they will in production.

⚠️ **GitHub.com Fallback** ⚠️