首页 > 解决方案 > 无法在 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();
});
});

谁能指出我哪里出错了,并请指出我正确的方向。

谢谢。

标签: javascriptnode.jsfirebasesinonsinon-chai

解决方案


推荐阅读