我有一个AppModule文件如下:
import { Module } from '@nestjs/common'
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'
@Module({
imports: [
RabbitMQModule.forRoot(RabbitMQModule, {
exchanges: [
{
name: 'my_rabbit',
type: 'direct',
},
],
uri: process.env.RABBITMQ_URI,
connectionInitOptions: { wait: true },
}),
],
})
export class AppModule {}我尝试过像这样使用@golevelup/nestjs-rabbitmq来模拟rabbitmq:
import { Module } from '@nestjs/common'
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
AppModule
],
})
.overrideProvider(AmqpConnection)
.useValue(createMock<AmqpConnection>())
.compile()
})这让我犯了错误:
[Nest] 2745 - 24/07/2022, 17:02:54 ERROR [AmqpConnection] Disconnected from RabbitMQ broker (default)
Error: connect ECONNREFUSED 127.0.0.1:5672如果我嘲笑整个rabbitmq模块,比如:
jest.mock('@golevelup/nestjs-rabbitmq')我会犯这样的错误:
Nest cannot create the AppModule instance.
The module at index [0] of the AppModule "imports" array is undefined.有人成功地模仿过RabbitMQ吗?如果可能的话请协助。
发布于 2022-08-23 16:24:18
我解决了这样模拟AmqpConnection的问题。
import { AmqpConnection } from "@nestjs-plus/rabbitmq";
import { TestingModule, Test } from "@nestjs/testing";
import { IntegrationQueueService } from "./integration-queue.service";
describe('IntegrationQueueService', () => {
type MockType<T> = {
[P in keyof T]?: jest.Mock<{}>;
};
const mockFactory: () => MockType<AmqpConnection> = jest.fn(() => ({
publish: jest.fn(() => AmqpConnection),
}))
let service: IntegrationQueueService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
IntegrationQueueService,
{
provide: AmqpConnection,
useFactory: mockFactory,
},
],
})
.compile();
service = module.get<IntegrationQueueService> (IntegrationQueueService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
})https://stackoverflow.com/questions/73097067
复制相似问题