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

461
Vistas
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 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