2014-02-19 49 views
7

我一直在研究几个摩卡/柴测试,我还没有找到一种很好的方式来运行我的测试,除了在每个测试中放置一个循环'它'测试和迭代一次和一次。问题是,如果我有数十或数百次测试,我不想一遍又一遍地写同样的for-loop。如何通过摩卡测试重复/循环

有没有更好的方法来做到这一点?特别是能够通过不同的测试参数同时循环所有测试的一种测试?

describe('As a dealer, I determine how many cards have been dealt from the deck based on', function(){ 

    console.log(this); 

    beforeEach(function(){ 
    var deck = new Deck(); 
    var myDeck = deck.getCards(); 
    }); 


    it('the number of cards are left in the deck', function(){ 
     for(var i = 1; i<=52; i++){ 
     myDeck.dealCard(); 
     expect(myDeck.countDeck()).to.equal(52-i); 
     } 
    }); 

    it('the number of cards dealt from the deck', function(){ 
     expect(myDeck.countDealt()).to.equal(i); 
    }); 

    it('the sum of the cards dealt and the cards left in the deck', function(){ 
     expect(myDeck.countDeck() + myDeck.countDealt()).to.equal(52) 
    }); 

}); 

回答

11

我实现neezer的解决方案在Loop Mocha tests?,其中包括把整个测试为封闭,并用循环执行它。

请注意,函数内的beforeEach()会循环使用,因为它每次测试执行52次。在beforeEach()函数中放置元素不是一个好主意,如果这些元素是动态的,并且每个循环不会被执行超过一次。

代码看起来像这样,它似乎工作。

var myDeck = new Deck(Card); 

function _Fn(val){ 

    describe('As a dealer, I determine how many cards have been dealt from the deck based on', function(){ 

     myDeck.dealCard(); 

     var cardCount = 0; 
     var dealtCount = 0; 

     cardCount = myDeck.countDeck(); 
     dealtCount = myDeck.countDealt(); 

     it('the number of cards are left in the deck', function(){ 
     expect(cardCount).to.equal(52-val); 
     }); 

     it('the number of cards dealt from the deck', function(){ 
     expect(dealtCount).to.equal(val); 
     }); 

     it('the sum of the cards dealt and the cards left in the deck', function(){ 
     expect(cardCount + dealtCount).to.equal(52); 
     }); 

    }); 

} 

for(var i = 1; i<=52; i++){ 
    _Fn(i); 
}