能否请您分享一些用于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.',
}
预期结果是异常错误,代码='auth / user-not-found'
答案 0 :(得分:3)
由于admin.auth
是一个getter,您不能将其存为一个函数,而只能将其作为存根(stub)对象返回一个函数。
您需要使用Sinon API中的stub.get(getterFn)
。
sinon.stub(admin, 'auth').get(() => () => ({
getUserByEmail: sinon.fake.rejects(noUserError)
}));
答案 1 :(得分:0)
使用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
});