firebase - 如何模拟/ stub react-native-firebase?

标签 firebase react-native testing jestjs react-native-firebase

有人知道为什么这不起作用吗?

我的 API 调用:

import firebase from 'react-native-firebase';

export default function getAuth() {
  return new Promise((resolve) => {
    firebase.auth().onAuthStateChanged((user) => {
      resolve(user);
    });
  });
}

我的单元测试失败,“预期调用一个断言,但收到零个断言调用”。

import firebase from 'react-native-firebase';

import getAuth from '../'; // eslint-disable-line

jest.mock('react-native-firebase', () => {
  return {
    auth: () => {
      return {
        onAuthStateChanged: () => {
          return Promise.resolve({
            name: 'Shaun',
          });
        },
      };
    },
  };
});

it('resolves a promise containing the user', async () => {
  expect.assertions(1);
  const response = await getAuth();
  expect(response).toEqual({ name: 'Shaun' });
});

最佳答案

  • 您返回了已解决的 Promise => 此后不会再调用任何内容。
  • 您的onAuthStateChanged是一个带有回调的函数

相反,将 onAuthStateChanged 的实现替换为:

onAuthStateChanged: jest.fn(cb => cb({ name: 'Shaun' }));

enter image description here

关于firebase - 如何模拟/ stub react-native-firebase?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50853124/

相关文章:

javascript - 在 React Native 中使用流为无状态功能组件定义 Prop 类型

cakephp - CakePHP 中的测试驱动开发

asp.net - 遍历文本框和标签

android - firebase auth UID 是否过期?

firebase - Firestore 使用动态键更新嵌套对象中的字段

android - 无法让 FirestoreRecyclerAdapter 显示项目

firebase - StreamBuilder 控件和 Firestore 定价

ios - react native 路由

react-native - 在 React Native 中页面加载时 StatusBarIOS 颜色变化

ruby-on-rails - rails : test a helper that needs access to the Rails environment (e. g。请求.完整路径)