arj
arj

Reputation: 983

jest RabbitMq AmqpConnection mock failed

I'm working on a NestJS application that interacts with RabbitMQ. I've written test cases for one of my APIs, and I'm trying to mock AmqpConnection. However, for some reason, the tests are still calling the actual RabbitMQ. Here's my code:

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

created a MockAmqpConnection file 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 }

When i run the test, it shows the below error

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

Solution tried:

  1. NestJS Mock RabbitMQ in Jest

  2. jest.mock('../../service/rabbitmq.health.indicator', () => { return { RabbitmqHealthIndicator: jest.fn().mockImplementation(() => ({ isHealthy: jest.fn().mockResolvedValue({ status: 'up' }) })) } })

  3. type MockType = { [P in keyof T]?: jest.Mock<{}> }

    const mockFactory: () => MockType = jest.fn(() => ({ publish: jest.fn(() => AmqpConnection) }))

Am new to jest testing.Did i miss anything?

Upvotes: 0

Views: 180

Answers (1)

arj
arj

Reputation: 983

Finally i found the solution. i have been create a mock baseconfig for my test environment. its look like this

jest.mock('../../../config/baseConfig', () => ({
    default: () => testEnvironmentConfiguration.baseConfig
}))

Upvotes: 0

Related Questions