2014-01-07 46 views
2

我想從node.js檢查一個特定的RabbitMQ交換是否存在。我正在使用Mocha作爲測試框架。我已經寫了相同的代碼,但我的期望似乎不正確。我希望交換變量在沒有交換時具有未定義的值,但事實並非如此。我正在使用amqp模塊與RabbitMQ交互。以下是代碼:如何從node.js檢查RabbitMQ中是否存在交換?

var should = require('should'); 
var amqp = require('amqp'); 

//Configuration 
var amqpConnectionDetails = { 
    'host':'localhost', 
    'port':5672, 
    'login':'guest', 
    'password':'guest' 
}; 

describe('AMQP Objects', function(){ 
    describe('Exchanges', function(){ 
     it('There should exist an exchange', function(done){ 
      var amqpConnection = amqp.createConnection(amqpConnectionDetails); 
      amqpConnection.on('ready', function(){ 
       var exchange = amqpConnection.exchange('some_exchange', {'passive':true, 'noDeclare':true}); 
       exchange.should.not.be.equal(undefined); 
       exchange.should.not.be.equal(null); 
       done(); 
      }); 
     }); 
    }); 
}); 

什麼是檢查交換存在的正確方法?

謝謝。

回答

2

如果交換不存在,將會拋出錯誤(「Uncaught Error:NOT_FOUND - no exchange'some_exchange'in vhost'/'」)。這意味着您應該添加一個「on error」方法來交換以捕獲交換不存在時它將拋出的錯誤。

其次,你應該從你的選項中刪除'noDeclare':true。

以下應工作(它會正常退出,如果匯率不存在,如果匯率不存在,會拋出異常):

var amqp = require('amqp'); 

//Configuration 
var amqpConnectionDetails = { 
    'host':'localhost', 
    'port':5672, 
    'login':'guest', 
    'password':'guest' 
}; 

describe('AMQP Objects', function(){ 
    describe('Exchanges', function(){ 
    it('There should not exist an exchange', function(done){ 
     var amqpConnection = amqp.createConnection(amqpConnectionDetails); 
     amqpConnection.on('ready', function(){ 
     var exchange = amqpConnection.exchange('some_exchange', {'passive':true}); 
     exchange.on('error', function(error) { 
      done(); 
     }); 
     exchange.on('open', function(exchange) { 
      throw("exchange exists!") 
      done(); 
     }); 
     }); 
    }); 
    }); 
});