Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
How to mock a Firebase set() with Sinon?

I am trying to test this Firebase access code

let writeHomePromise = admin
  .database()
  .ref(
    "sm_matches/" +
    match.date +
    "/" +
    match.homeTeam.name +
    "/homeNGSPlayers"
  )
  .set(match.homePlayers);

using Sinon.

I create a match with

    const match = {
        'date' : '2902199',
        'homeTeam' : '{"name" : "My_team"}',
        'homePlayers'  : ["Nomran Mailer", "Peter Bonetti"],
        'awayPlayers': ["Ernst Blofeld", "Postman Pat"],
      };

And I am trying, unsuccessfully, to mock that code with

    let refStub = sinon.stub();
    let setStub = sinon.stub();
    refStub.withArgs('sm_matches/2902199/My_team/homeNGSPlayers').returns(
        {push: () => ({key: 'fakeKey', set: setStub})}
        );

which gives me TypeError: Cannot read property 'set' of undefined.

This is my first foray into Sinon, and even something this simple is giving me problems.

What am I doing wrongly?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I believe that you should call admin.initializeApp() before using any of the Firebase services. Below example using the offline mode testing strategy.

Write siloed and offline unit tests with no side effects. This means that any method calls that interact with a Firebase product (e.g. writing to the database or creating a user) need to be stubbed. Using offline mode is generally not recommended if you have Cloud Firestore or Realtime Database functions, since it greatly increases the complexity of your test code.

Try stub methods like this:

index.js:

const admin = require('firebase-admin');

admin.initializeApp();

function main() {
  const match = {
    date: '2902199',
    homeTeam: { name: 'My_team' },
    homePlayers: ['Nomran Mailer', 'Peter Bonetti'],
    awayPlayers: ['Ernst Blofeld', 'Postman Pat'],
  };
  return admin
    .database()
    .ref('sm_matches/' + match.date + '/' + match.homeTeam.name + '/homeNGSPlayers')
    .set(match.homePlayers);
}

module.exports = main;

index.test.js:

const sinon = require('sinon');
const admin = require('firebase-admin');

describe('71267791', () => {
  it('should pass', async () => {
    const adminInitStub = sinon.stub(admin, 'initializeApp');
    const databaseService = {
      ref: sinon.stub().returnsThis(),
      set: sinon.stub(),
    };
    const databaseStub = sinon.stub().returns(databaseService);

    Object.defineProperty(admin, 'database', { get: () => databaseStub });
    const main = require('./');
    await main();
    sinon.assert.calledOnce(adminInitStub);
    sinon.assert.calledOnce(admin.database);
    sinon.assert.calledWithExactly(databaseService.ref, 'sm_matches/2902199/My_team/homeNGSPlayers');
    sinon.assert.calledWithExactly(databaseService.set, ['Nomran Mailer', 'Peter Bonetti']);
  });
});

Test result:

  71267791
    ✓ should pass (655ms)


  1 passing (661ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------

package versions:

"firebase-admin": "^10.0.2",
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda