【问题标题】:How to handle RabbitMQ Connection on Node.js to use on Jest?如何处理 Node.js 上的 RabbitMQ 连接以在 Jest 上使用?
【发布时间】:2019-07-26 14:39:24
【问题描述】:

我有一个下面的代码 sn-p 来连接 RabbitMQ,它工作正常,但在测试用例中,我得到一个 异步操作 错误。我尝试使用this.start();this.start().then

var amqplib = require('amqplib');
const { amqp: { uri: amqpURI } } = require('../config');

class Broker {
    constructor(url) {
        this.queue = 'user';
        this.url = url;
        //this.start(); Old
        this.start().then(function (conn) {
            console.log(conn);
        });
    }
    start() {
        return amqplib.connect(this.url).then((conn) => {
            conn.on("close", () => {
                this.conn = null;
                return this.retryConnection();
            });
            return conn;
        }).catch((error) => {
        });
    }

    .....

}

注意:当我评论 this.start(); 时,错误消失了

错误:

Jest 在测试运行完成后一秒没有退出。

这通常意味着存在未执行的异步操作 在您的测试中停止。考虑运行 Jest --detectOpenHandles 解决此问题。

【问题讨论】:

    标签: javascript node.js rabbitmq jestjs


    【解决方案1】:

    我写了一个代码来在连接关闭时重新连接 RabbitMQ。因此,当我关闭 Jest.js 上的连接时,它会尝试再次重新连接 RabbitMQ。

    现在,由于error,我只重新连接RabbitMQ on close

    conn.on("close", (err) => {
        if (err) {
            this.conn = null;
            return this.retryConnection();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-12
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      • 2011-06-01
      • 2019-01-30
      相关资源
      最近更新 更多