Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda