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

469
Visualizações
How to mock Google Pub/Sub in JavaScript?

Context

I need to test a function that publishes events using Google Pub/Sub:

  • Given the event_id, it builds event be published
const event = {
    data: Buffer.from(event_id).toString('base64'),
  };

const message = await pubSubClient.topic(topicName).publish(event);
console.log(`Message ${message} published.`);

Problem

My function provides some logs if the event is published successfully and I'd like to use the logs to verify if the behavior is correct.

The problem is that I don't know how to mock the pub/sub instance itself in javascript and make it return specific value or throw exception, given and event_id.

So I want references/pointers to:

  1. How to mock PubSub instance with publish method using different returns

Example:

jest.mock('@google-cloud/pubsub', () => ({
  __esModule: true,
  PubSub: jest.fn().mockImplementation(() => ({
    topic: mockTopic,
    publish: mockPublish,
  })),
}));

test('succeeds to publish message when event_id is valid', () => {
    myFunction(anyEventId);
    expect(console.log).toBeCalledTimes(1);
    expect(console.log).toHaveBeenLastCalledWith(
      `Message published.`
    );
  });

Reference

https://cloud.google.com/functions/docs/samples/functions-pubsub-unit-test

https://jestjs.io/pt-BR/docs/mock-function-api#mockfnmockreturnvaluevalue

about 4 years ago · Juan Pablo Isaza
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