2013-07-15 191 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毫秒的停顿似乎相当随意。我真的说:“在我认为它会超时之前,跳入并说好。”