【问题标题】:Mocking PubSub publish method模拟 PubSub 发布方法
【发布时间】:2022-01-11 11:51:18
【问题描述】:

我正在关注这个Mock new Function() with Jest 来模拟 PubSub,不幸的是没有运气。

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 }))

我有两个错误。

第一个是一行

PubSub as jest.Mock<PubSub>

类型 'typeof PubSub' 到类型 'Mock' 的转换可能是一个错误,因为这两种类型都没有与另一种充分重叠。如果这是故意的,请先将表达式转换为“未知”。

第二个在最后一行

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

类型参数 '() => { publish: jest.Mock; }' 不能分配给 '(...args: any) => PubSub' 类型的参数。

如何模拟这个?

【问题讨论】:

    标签: javascript node.js typescript google-cloud-platform jestjs


    【解决方案1】:

    找到答案

    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,
      })),
    }))
    

    【讨论】:

      猜你喜欢
      • 2022-08-17
      • 2021-12-13
      • 1970-01-01
      • 2020-08-25
      • 2021-12-28
      • 2022-12-10
      • 1970-01-01
      • 2021-07-04
      • 2020-05-02
      相关资源
      最近更新 更多