模拟 PubSub 发布方法
Mocking PubSub publish method
我正在关注这个 来模拟 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>
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.
第二个在最后一行
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'.
我该如何模拟这个?
找到答案
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,
})),
}))
我正在关注这个
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>
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.
第二个在最后一行
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'.
我该如何模拟这个?
找到答案
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,
})),
}))