Karl Taylor
Karl Taylor

Reputation: 5279

How to mock LayoutAnimation when testing React Native with Jest

I am using Jest and react-native-testing-library to test my components.

In one of my components I have the following code:

const handleToggleFilters = () => {
  LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
  setPostFiltersActive(!postFiltersActive);
};

However, when testing my component, I get the following error

    TypeError: require(...).configureNextLayoutAnimation is not a function

      82 |
      83 |   const handleToggleFilters = () => {
    > 84 |     LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
         |                                  ^
      85 |     setPostFiltersActive(!postFiltersActive);
      86 |   };
      87 |

I added jest.mock('react-native') to my setup.js file but it then started complaining about other missing entities through the rest of my test suite ... do I have to mock the entire react-native library for this to work?

What is the best way around this?

Upvotes: 3

Views: 1964

Answers (1)

Karl Taylor
Karl Taylor

Reputation: 5279

After looking at certain tests from react-native on github, it looked like they simple mocked the file themselves.

// Libraries/Components/Keyboard/__tests__/Keyboard-test.js

jest.mock('../../../LayoutAnimation/LayoutAnimation');

So in my setup.js file I simply did

jest.mock(
  '../node_modules/react-native/Libraries/LayoutAnimation/LayoutAnimation.js',
);

And my tests passed.

Upvotes: 7

Related Questions