Context
I need to test a function that publishes events using Google Pub/Sub:
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:
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