我一直在进行一些mocha/chai测试,但除了在每个“it”测试中放置一个循环并一次又一次地迭代外,我仍然没有找到一种在多种可能性下运行测试的好方法。问题是,如果我有数十或数百个测试,我不想一遍又一遍地编写相同的for循环。
有没有更优雅的方式做到这一点?尤其是一种可以同时循环使用不同测试参数进行的所有测试吗?
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)
});
});
最佳答案
我在Loop Mocha tests?上实现了neezer的解决方案,其中涉及将整个测试放入一个闭包中并通过循环执行它。
请注意,该循环与函数中的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);
}
关于tdd - 如何重复/循环进行 Mocha 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21890010/