2013-07-15 159 views
2

我有一個Faye發佈/訂閱服務器,只有在消息已經發送給其他訂閱者時纔會向新訂閱者發送消息。我正在使用摩卡進行單元測試。測試摩卡的預期超時

這個測試工作,以確認的基本功能:

it('should send a special message to new subscribers', function(done){ 
     testerPubSub.setLastJsonContent('some arbitrary content'); 
     var subscription = client.subscribe("/info", function(message) { 
      assert.equal(true, message.text.indexOf('some arbitrary content') !== -1, 'new subscriber message not sent'); 
      done(); 
     }); 
     subscription.cancel(); 
    }); 

但我現在想考那裏一直沒有送到之前的用戶信息的情況。這個測試可能是這樣的:

it('should not send a special message to new subscribers if no data has been retrieved', function(done){ 
     testerPubSub.setLastJsonContent(null); 
     var messageReceived = false; 
     var subscription = client.subscribe("/sales", function(message) { 
      messageReceived = true; 
     }); 

     ////need to magically wait 2 seconds here for the subscription callback to timeout 

     assert.equal(false, messageRecieved, 'new subscriber message received'); 
     subscription.cancel; 
     done(); 
    }); 

當然,神奇的睡眠功能是有問題的。有沒有更好的方法來做這種「我希望回調永遠不會被解僱」的測試?

謝謝, 邁克

回答

0

我想到了一個可能的解決方案,但它是一個有點太依賴於時間對我來說,把它作爲解決方案:

it('should not send a special message to new subscribers if no data has been retrieved', function(done){ 
     testerPubSub.setLastJsonContent(null); 
     var messageReceived = false; 
     var subscription = client.subscribe("/sales", function(message) { 
      assert.fail(message.text, '', 'Should not get message', '='); 
     }); 
     setTimeout(function(){ 
      done(); 
     }, 1500); 

     subscription.cancel; 
    }); 

該測試通過,但1500毫秒的停頓似乎相當隨意。我真的說:「在我認爲它會超時之前,跳入並說好。」