Rodrigo
Rodrigo

Reputation: 391

Mocking PubSub publish method

I am following this Mock new Function() with Jest to mock PubSub, unfortunately no luck.

jest.mock('@google-cloud/pubsub', () => jest.fn())

...

const topic = jest.fn((name) => ({ '@type': 'pubsub#topic', name }))
const publish = jest.fn((data) => ({ '@type': 'Buffer', data }))

const mockedPubSub = PubSub as jest.Mock<PubSub>
mockedPubSub.mockImplementation(() => ({ topic }))

I got two erros.

The first one is one the line

PubSub as jest.Mock<PubSub>

Conversion of type 'typeof PubSub' to type 'Mock<PubSub, any>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

And the second one is on the last line

mockedPubSub.mockImplementation(() => ({ publish }))

Argument of type '() => { publish: jest.Mock<{ '@type': string; data: any; }, [data: any]>; }' is not assignable to parameter of type '(...args: any) => PubSub'.

How can I mock this?

Upvotes: 0

Views: 2675

Answers (1)

Rodrigo
Rodrigo

Reputation: 391

Found the answer

const mockTopic = jest.fn().mockImplementation(() => ({
  get: jest.fn(),
  publish: jest.fn(),
}));

const mockPublish = jest.fn();

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

Upvotes: 4

Related Questions