Unit Testing Components with Jest in React Native. Approaches

Daniil Sitdikov
2 min readApr 26, 2019

--

If you are interested in technical details, how it integrates into the project and common problems resolutions: read this article.

I’ve used react-native-testing-library. It has similar API as react-testing-library but includes fewer abilities. A full API is located here.

Let’s get started with a simple example:

  1. A user inputs some title
  2. A component finds 1 the most relevant item.
Code 1 — Piece of some component

In this article, I don’t use the unnecessary code (such as the whole component, logic of the filter, etc.)

There are 2 approaches to testing:

Snapshots

Code 2 — Snapshot testing example

Advantages:

  • Good reliability. It covers the whole state of component: makeup, small details, etc.

Disadvantages:

  • It could be huge like in an example below and it’s hard to find and change something (if business-requirements has been changed and you wanna update your snapshot for next test-driven development).
Pic. 1 — A huge snapshot

Query

It finds a node or list of nodes in the tree of some component.

Code 3 — An example of testing by node’s content

Advantages:

  • It looks like more as specification and easy to read and understand
  • It’s ready for use for TDD

Disadvantages:

  • It’s a very small point testing and it can’t guarantee that bugs in the resulting state of the component will be found.

There is a full API (at the moment of writing article) of query functions here:

queryByName: (name: React.ReactType | string)
queryByType: <P>(type: React.ComponentType<P>)
queryByText: (name: string | RegExp)
queryByPlaceholder: (placeholder: string | RegExp)
queryByProps: (props: Record<string, any>)
queryByTestId: (testID: string)
queryAllByName: (name: React.ReactType | string)
queryAllByType: <P>(type: React.ComponentType<P>)
queryAllByText: (text: string | RegExp)
queryAllByPlaceholder: (placeholder: string | RegExp)
queryAllByProps: (props: Record<string, any>)

Article about troubles resolutions, mocking store, etc.

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

--

--