简体   繁体   English

使用 Jest 测试 React Native 时如何模拟 LayoutAnimation

[英]How to mock LayoutAnimation when testing React Native with Jest

I am using Jest and react-native-testing-library to test my components.我正在使用 Jest 和react-native-testing-library来测试我的组件。

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?我将jest.mock('react-native')到我的 setup.js 文件中,但它随后开始通过我的测试套件的其余部分抱怨其他缺少的实体......我是否必须为此模拟整个react-native库上班?

What is the best way around this?解决这个问题的最佳方法是什么?

After looking at certain tests from react-native on github, it looked like they simple mocked the file themselves.在查看了 github 上react-native某些测试后,看起来他们自己简单地模拟了文件。

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

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

So in my setup.js file I simply did所以在我的setup.js文件中我只是做了

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

And my tests passed.我的测试通过了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM