如何使用 sinon 存根 require('firebase-admin').auth().getUserByEmail()?

use*_*611 3 node.js sinon firebase-authentication

您能否分享一些用于 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);
Run Code Online (Sandbox Code Playgroud)

但它返回

  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.',
  }
Run Code Online (Sandbox Code Playgroud)

预期结果是异常错误代码 = 'auth/user-not-found'

Ron*_*gar 8

由于admin.auth是 getter,您不能将其作为函数存根,而是作为返回带有存根对象的函数的 getter。您需要使用stub.get(getterFn)来自 Sinon API。

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


use*_*611 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
  });
Run Code Online (Sandbox Code Playgroud)