NestJS中Jest模拟AmqpConnection失败,仍调用真实RabbitMQ
NestJS测试中模拟AmqpConnection仍调用真实RabbitMQ的问题
开发一个与RabbitMQ交互的NestJS应用,编写API测试用例时尝试模拟AmqpConnection,但测试仍在调用真实的RabbitMQ。作为Jest测试新手,想排查是否遗漏关键步骤。
代码示例
MyControllerSpec.ts
describe('MyController', () => { let app let module: TestingModule beforeEach(async () => { jest.clearAllMocks() module = await Test.createTestingModule({ controllers: [MyController], imports: [AppModule], providers: [ { provide: AmqpConnection, useClass: MockAmqpConnection } ] }).compile() app = module.createNestApplication() await app.init() }, 10000) afterAll(async () => { await app.close() }) it('should be defined', () => { const controller = module.get<MyController>( MyController ) expect(controller).toBeDefined() }) it('should call MyService.get with queryParams', async () => { //code }) })
MockAmqpConnection.ts
class MockAmqpConnection { private _connected: boolean = true get connected(): boolean { return true } async connect(): Promise<void> { this._connected = true } async disconnect(): Promise<void> { this._connected = false } } export { MockAmqpConnection }
报错信息
Please migrate your code to use AWS SDK for JavaScript (v3). For more information, check the migration guide at https://a.co/7PzMCcy (Use `node --trace-warnings ...` to show where the warning was created) [Nest] 32466 - 05/09/2024, 10:27:07 AM ERROR [AmqpConnection] Disconnected from RabbitMQ broker (default) Error: getaddrinfo ENOTFOUND <actual rabitmq url> Error: Failed to connect to a RabbitMQ broker within a timeout of 5000ms at workspace-nestjs/n1ab/node_modules/@golevelup/nestjs-rabbitmq/src/amqp/connection.ts:192:17
已尝试的解决方案
- 查找参考了NestJS模拟RabbitMQ的相关测试方案
- 使用
jest.mock模拟RabbitmqHealthIndicator:
jest.mock('../../service/rabbitmq.health.indicator', () => { return { RabbitmqHealthIndicator: jest.fn().mockImplementation(() => ({ isHealthy: jest.fn().mockResolvedValue({ status: 'up' }) })) })
- 使用MockType创建模拟工厂:
type MockType<T> = { [P in keyof T]?: jest.Mock<{}> } const mockFactory: () => MockType<AmqpConnection> = jest.fn(() => ({ publish: jest.fn(() => AmqpConnection) }))
内容的提问来源于stack exchange,提问作者arj
相关产品推荐
相关产品推荐

