How to test and mock pubsub subscriber data with Jest?

Viewed 69

For this subscriber class:

type Post = {
  id: string;
  name: string;
};

export class postHandler extends BaseEventHandler {
  public handle = async (message: Message) => {
    const { data: postBuffer } = message;
    const post: Post = JSON.parse(`${postBuffer}`);

    # ..

baseEventHandler.ts

import { Message } from "@google-cloud/pubsub";

export abstract class BaseEventHandler {
  handle = async (_message: Message) => {};
}

I want to mock the message data postBuffer as

{
  "id": 1,
  "name": "Awesome"
}

From the Google docs, it provides unit test as

const assert = require('assert');
const uuid = require('uuid');
const sinon = require('sinon');

const {helloPubSub} = require('..');

const stubConsole = function () {
  sinon.stub(console, 'error');
  sinon.stub(console, 'log');
};

const restoreConsole = function () {
  console.log.restore();
  console.error.restore();
};

beforeEach(stubConsole);
afterEach(restoreConsole);

it('helloPubSub: should print a name', () => {
  // Create mock Pub/Sub event
  const name = uuid.v4();
  const event = {
    data: Buffer.from(name).toString('base64'),
  };

  // Call tested function and verify its behavior
  helloPubSub(event);
  assert.ok(console.log.calledWith(`Hello, ${name}!`));
});

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

By this way how can I make the message data in my case? Since the example is using a pure string but in my case it's a json.

0 Answers
Related