【问题标题】:How to repeat/loop through mocha tests如何重复/循环通过 mocha 测试
【发布时间】:2014-02-19 19:08:19
【问题描述】:

我一直在进行一些 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)
    });

});

【问题讨论】:

    标签: tdd mocha.js chai


    【解决方案1】:

    我在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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2015-07-16
      • 2016-05-30
      • 1970-01-01
      相关资源
      最近更新 更多