javascript - 无法在 Sinon 中对 Firebase 功能进行单元测试
问题描述
我正在尝试使用 mocha、chai、sinon 对包含 firebase 查询的 JavaScript 承诺进行单元测试。我正在尝试使用 sinon 模拟数据库,而不是实际向数据库发出请求。但是,我无法正确实现它。
这是我在文件“/services/pr_services”中的承诺:
exports.getUserInfo = (userId) => {
return new Promise((resolve, reject) => {
const userProfile = {};
const userProfileRef = database.ref('profiles').child(userId);
userProfileRef.once('value', (snap) => {
if (snap.exists()) {
const userProfileData = snap.val();
resolve(userProfile);
} else {
reject();
}
});
});
};
该变量database
包含数据库配置,如凭据、数据库 url 等
这是我的测试用例代码:
const chai = require('chai');
const sinon = require('sinon');
const admin = require('firebase-admin');
const database = require('../database');
const services = require('../services/pr_services');
const should = chai.should();
describe('Database functions', () => {
let adminInitStub;
before(() => {
adminInitStub = sinon.stub(admin, 'initializeApp');
});
describe('get profile info', () => {
it('should return a non empty object', (done) => {
beforeEach(() => {
services.getUserInfo = sinon.stub();
});
afterEach(() => {
services.getUserInfo.reset();
});
const userId = 'jim123';
const snap = {
name: 'Jim Dani',
address: 'Porto'
};
const userProfileRef = database.ref('profiles').child(userId);
userProfileRef.once('value').returns(Promise.resolve(snap));
services.getUserInfo
.then(info => {
info.should.be.a('object');
info.should.equal(snap);
done();
})
.catch(err => {
should.not.exist(err);
done();
});
});
});
after(() => {
adminInitStub.restore();
test.cleanup();
});
});
谁能指出我哪里出错了,并请指出我正确的方向。
谢谢。
解决方案
推荐阅读
- android - 应用程序不能使用 JobIntentService 安排超过 100 个不同的作业
- java - 使用 java validate 以特定格式打印字符串
- asp.net-core - 项目必须为配置提供一个值
- django - 将对象名称保存到子对象的 ForeignKey 字段中 - Django
- javascript - 如何在 Angular 的 ngOnInit 中使用 Typescript 访问器?
- optimization - 我如何总结不受控制的集合?
- wordpress - 如何在前端设置自定义帖子类型
- python - 如何从平面图图像中检测门窗?
- java - 如何从文本文件中检查用户名和密码的有效性
- javascript - 即使在不可变更新时,状态中的元素也会在 react.js 中被删除