【问题标题】:How to stub require('firebase-admin').auth().getUserByEmail() with sinon?如何使用 sinon 存根 require('firebase-admin').auth().getUserByEmail()?
【发布时间】:2019-12-25 05:55:44
【问题描述】:

您能否分享一些用于 firebase-admin 身份验证的 Sinon 存根示例。挑战在于初始化 Firebase 管理应用程序以获取更多存根。

我尝试了下一个代码

  const admin = require('firebase-admin');
  sinon.stub(admin, 'initializeApp');
  var noUserError = new Error('error');
  noUserError.code = 'auth/user-not-found';
  sinon.stub(admin, 'auth').returns({
    getUserByEmail: sinon.fake.rejects(noUserError)
  });
  var err = await admin.auth().getUserByEmail(email);
  console.error(err);

但它会返回

  Error (FirebaseAppError) {
    codePrefix: 'app',
    errorInfo: {
      code: 'app/no-app',
      message: 'The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.',
    },
    message: 'The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.',
  }

预期结果是异常 Error with code = 'auth/user-not-found'

【问题讨论】:

    标签: node.js firebase-authentication sinon


    【解决方案1】:

    使用 firebase-mock 有所帮助。

    https://github.com/soumak77/firebase-mock

      const firebasemock = require('firebase-mock');
      const mockauth = new firebasemock.MockAuthentication();
      const mockdatabase = new firebasemock.MockFirebase();
      const mocksdk = new firebasemock.MockFirebaseSdk(
        (path) => {
          return path ? mockdatabase.child(path) : mockdatabase;
        },
        () => {
          return mockauth;
        }
      );
      mocksdk.auth().autoFlush();
    
      proxyquire('../index', {
        'firebase-admin': mocksdk
      });
    

    【讨论】:

      【解决方案2】:

      由于admin.auth 是一个getter,你不能将它作为一个函数存根,而是作为一个getter,它用你的存根对象返回一个函数。 您需要使用 Sinon API 中的stub.get(getterFn)。

      sinon.stub(admin, 'auth').get(() => () => ({
        getUserByEmail: sinon.fake.rejects(noUserError)
      }));
      

      【讨论】:

        猜你喜欢
        • 2017-10-18
        • 1970-01-01
        • 1970-01-01
        • 2018-06-24
        • 2015-10-13
        • 2015-08-18
        • 1970-01-01
        • 1970-01-01
        • 2018-10-15
        相关资源
        最近更新 更多