Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

460
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!