mock-with-jest.mo

Why

Most teams at BAM use jest for testing their react components. One of the most frequent andon is about mocks.

Typical use case: "My component's snapshot test was passing but then I imported a module and now the test is broken :'("

Prerequisites

Have jest installed ;)

Steps

In this MO you will learn to:

  • mock some method on an imported module

  • mock an imported component

  • mock a class that is used for both rendering a component AND using static methods

Example 1: mock some method on an imported module

File to be tested:

Test file with snapshot test:

Even better

In the example above we are mocking a native module (react-native-permissions). Since you always need to mock a native module, you should centralize the mock definition in order to avoid redefining it in numerous test files. Here is how to do it:

Example 2: Mock one of your own components

In the example below, we chose to mock the Votes component when we added a container with graphql logic around the original Votes component

File to be tested:

Test file with snapshot test:

Example 3: Mock a class that is used for both rendering a component AND using static methods

In the example below we use the react-rte/lib/RichTextEditor module to build our own state-controlled markdown input component.

File to be tested:

Centralized mock (see Example 1, section "Even better"):

Last updated