尝试在 Jest 测试中渲染 react-native-reanimated 节点时出现“TypeError”

daw*_*623 4 jestjs react-native react-native-reanimated

当尝试在 Jest 中渲染我的应用程序以进行一些集成测试时,我收到以下错误:

    TypeError: Cannot read property 'createNode' of undefined

      at AnimatedParam.createNode [as __nativeInitialize] (node_modules/react-native-reanimated/src/core/AnimatedNode.js:126:24)
      at AnimatedParam.__nativeInitialize [as __attach] (node_modules/react-native-reanimated/src/core/AnimatedNode.js:71:10)
      at new __attach (node_modules/react-native-reanimated/src/core/AnimatedParam.js:11:10)
      at createAnimatedParam (node_modules/react-native-reanimated/src/core/AnimatedParam.js:71:10)
      at createAnimatedFunction (node_modules/react-native-reanimated/src/core/AnimatedFunction.js:38:17)
      at Object.<anonymous> (node_modules/react-native-reanimated/src/derived/interpolate.js:17:39)
Run Code Online (Sandbox Code Playgroud)

它抱怨的代码react-native-reanimated如下所示:

  __nativeInitialize() {
    if (!this.__initialized) {
      ReanimatedModule.createNode(this.__nodeID, { ...this.__nodeConfig });
      this.__initialized = true;
    }
  }
Run Code Online (Sandbox Code Playgroud)

并且是来自库ReanimatedModule的类型别名。除此之外,我还没有找到任何有助于解决此问题的有用信息。NativeModulereact-native

这里特别奇怪的是,据我所知,我没有直接react-native-reanimated在我的代码库中使用,并且我能找到的唯一使用它的库组件没有在正在测试的组件中呈现。

我无法以任何合理的方式精简我的代码来重现此问题,并且相关代码受公司版权保护,因此我无法共享存储库。我将继续尝试在一个小示例中重现该错误,但我想将这个问题提出来,以防有人对此问题有任何经验。

小智 5

如果您需要模拟,react-native-reanimated则不必手动执行,因为他们现在在模块本身中提供了模拟。

只需将此行添加到您的jest.setup.js文件中:

jest.mock('react-native-reanimated', () =>
  require('react-native-reanimated/mock')
);
Run Code Online (Sandbox Code Playgroud)

此 PR 对此进行了介绍:https://github.com/software-mansion/react-native-reanimated/pull/276/files#diff-1377ba307a14fcbe31e128f4753b73301a43967a417c744f144f9ae5d77f67d5R7