如何正确模拟利用本机代码的React Native模块? [英] How to correctly mock a React Native module that utilizes native code?

查看:90
本文介绍了如何正确模拟利用本机代码的React Native模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TypeScript构建一个React Native应用程序.我正在使用react-native-firebase进行通知.此外,我还在单元测试中使用Jest和Enzyme.

I'm building a React Native app with TypeScript. I'm using react-native-firebase for my notifications. I'm furthermore using Jest and Enzyme for my unit tests.

我具有以下包装器功能来检查用户权限:

I have the following wrapper function to check the users permissions:

export const checkPermissions = (): Promise<boolean> =>
  new Promise((resolve, reject) => {
    firebase
      .messaging()
      .hasPermission()
      .then(enabled => {
        if (enabled) {
          resolve(enabled);
        } else {
          firebase
            .messaging()
            .requestPermission()
            .then(resolve)
            .catch(reject);
        }
      });
  });

现在我想测试该函数是否被调用.

Now I want to test if the function gets called.

这是我写的测试:

import * as firebase from "react-native-firebase";
import { checkPermissions } from "./notificationHelpers";

jest.mock("react-native-firebase");

describe("checkPermissions", () => {
  beforeEach(async done => {
    jest.resetAllMocks();
    await checkPermissions();
    done();
  });

  it("should call firebase.messaging().hasPermission()", () => {
    expect(firebase.messaging().hasPermission).toHaveBeenCalledTimes(1);
  });
});

这会引发错误:

 FAIL  app/services/utils/core/notificationHelpers/notificationHelpers.test.ts
  ● Test suite failed to run

    RNFirebase core module was not found natively on iOS, ensure you have correctly included the RNFirebase pod in your projects `Podfile` and have run `podinstall`.

     See http://invertase.link/ios for the ios setup guide.

      Error: RNFirebase core module was not found natively on iOS, ensure you have correctly included the RNFirebase pod in your projects `Podfile` and haverun `pod install`.

所以在我看来,使用本机代码的模块不能简单地通过自动模拟来实现.

So it seems to me that modules that use native code can't simply by auto-mocked.

所以我尝试手动模拟它.在我的根项目中与node_modules相邻的文件夹__mocks__中,我创建了一个名为react-native-firebase.ts的文件,如下所示:

So I tried to manually mock it. Inside a folder __mocks__ that's within my root project adjacent to node_modules I created a file called react-native-firebase.ts, which looks like this:

const firebase = {
  messaging: jest.fn(() => ({
    hasPermission: jest.fn(() => new Promise(resolve => resolve(true)))
  }))
};

export default firebase;

但是此代码也失败了,因为据称未定义firebase.messaging.

But this code also fails, because firebase.messaging is allegedly undefined.

这篇关于如何正确模拟利用本机代码的React Native模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆