我正在尝试编写TypeScript类来包装RabbitMQ功能并使用Jest进行测试。在测试中,我创建一个新类,并afterAll
取消绑定队列,删除交换并关闭连接。但是,当我尝试它时,出现Channel ended, no reply will be forthcoming
错误。我是RabbitMQ和Jest的新手,所以我可能会在这里完全离开。关于如何正确执行此操作的任何想法?
import * as amqp from 'amqplib';
import { IRabbitMQ, IQueue } from './IRabbitMQ.interface';
export class AMQPBroker {
private amqpConnection: amqp.Connection;
private amqpChannel: amqp.Channel;
private amqpSettings: IRabbitMQ;
private exchanges: string[];
private queues: IQueue[];
constructor(config: IRabbitMQ) {
this.amqpSettings = config;
this.exchanges = config.exchanges;
this.queues = config.queues;
}
async start() {
try {
this.amqpConnection = await amqp.connect(this.amqpSettings.serverName);
this.amqpChannel = await this.amqpConnection.createChannel();
this.exchanges.forEach((ex) => {
this.amqpChannel.assertExchange(ex, 'topic', { durable: false });
});
this.queues.forEach(async (q) => {
await this.amqpChannel.assertQueue(q.name, { exclusive: true });
await this.amqpChannel.bindQueue(q.name, this.exchanges[0], q.key);
});
} catch (e) {
console.log(e);
}
}
async close() {
try {
this.queues.forEach(async (q) => {
await this.amqpChannel.unbindQueue(q.name, this.exchanges[0], q.key);
await this.amqpChannel.deleteQueue(q.name);
});
this.exchanges.forEach(async (ex) => {
this.amqpChannel.deleteExchange(ex);
});
await this.amqpChannel.close();
await this.amqpConnection.close();
} catch (e) {
console.log(e);
}
}
}
测试:
import 'jest';
import { AMQPBroker } from '../rabbitMQ.main';
import { IRabbitMQ } from '../IRabbitMQ.interface';
const rabbitMQ: IRabbitMQ = {
serverName: 'amqp://localhost',
persistenceLevel: 0,
exchanges: [
'temp',
],
queues: [
{
name: 'temp-read-queue',
key: 'temp.event.read',
},
{
name: 'temp-read-queue2',
key: 'temp.event.read2',
},
],
};
describe('RabbitMQ Lib Tests', () => {
let broker: AMQPBroker;
beforeAll(async (done) => {
broker = new AMQPBroker(rabbitMQ);
await broker.start();
done();
});
test('New rabbitMQ class was created', async (done) => {
console.log('here');
done();
});
afterAll(async (done) => {
await broker.close();
done();
});
});