我正在开发一个与 RabbitMQ 交互的 NestJS 应用程序。我已经为我的一个 API 编写了测试用例,并且正在尝试模拟 AmqpConnection。然而,由于某种原因,测试仍在调用实际的 RabbitMQ。这是我的代码:
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 文件 MockAmqpConnection
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
尝试过的解决方案:
jest.mock('../../service/rabbitmq.health.indicator', () => { 返回 { RabbitmqHealthIndicator: jest.fn().mockImplementation(() => ({ isHealthy: jest.fn().mockResolvedValue({ status: 'up' }) })) } })
类型模拟类型 = { [P in keyof T]?: jest.Mock<{}> }
const mockFactory: () => MockType = jest.fn(() => ({ 发布:jest.fn(() => AmqpConnection) }))
我是玩笑测试的新手。我错过了什么吗?
终于我找到了解决方案。我已经为我的测试环境创建了一个模拟基本配置。它看起来像这样
jest.mock('../../../config/baseConfig', () => ({
default: () => testEnvironmentConfiguration.baseConfig
}))