单元测试 React Native:NativeModules.RNViewShot 未定义。确保库已链接到本机端

Eri*_*rth 6 reactjs jestjs react-native

当我对应用程序中的各个组件运行一些单元测试时,我不断收到这个恼人的警告:

NativeModules.RNViewShot is undefined. Make sure the library is linked on the native side.
Run Code Online (Sandbox Code Playgroud)

在我的根目录中,我运行'react-native link'并在控制台中看到:

rnpm-install info Platform 'ios' module react-native-view-shot is already linked
rnpm-install info Platform 'android' module react-native-view-shot is already linked
rnpm-install info Linking assets to ios project
rnpm-install info Linking assets to android project
rnpm-install info Assets have been successfully linked to your project
Run Code Online (Sandbox Code Playgroud)

这里给出了什么 > ?

Platform: MacOS,
Editor: VSCode,
react: "16.4.0",
react-native: "0.54.2",
react-native-view-shot: "^2.4.0",
Run Code Online (Sandbox Code Playgroud)

sky*_*lor 3

您需要为这个库进行模拟。

例如

  1. 在app中创建目录__mocks __
  2. 创建文件react-native-view-shot.js
  3. 在该文件中,添加以下内容:

    jest.mock('react-native-view-shot', () => {
      return {
        // whatever function you want to mock, e.g capture: jest.fn()
      };
    });
    
    Run Code Online (Sandbox Code Playgroud)