2013-04-15 19 views
2

我目前正在使用Karma作爲JS跑步者在Jasmine寫測試。能有多個「之」內「描述」象下面這樣:在寫「茉莉花測試」(BDD)時,在「描述」中多個「it」

describe('PhoneCat controllers', function() { 

    describe('PhoneListCtrl', function(){ 

    it('should create "phones" model with 3 phones', function() { 
     var scope = {}, 
      ctrl = new PhoneListCtrl(scope); 

     expect(scope.phones.length).toBe(2); 

    it('should create "greetings" models with 3 greeting', funciton(){ 
     var scope = {}, 
     ctrl = new PhoneListCtrl(scope); 

     expect(scope.greetings.length).toBe(3); 

    }); 
    }); 
    }); 
}); 

目前,它失敗了,但你如何寫一個測試,而不是多餘的(在這種情況下,不必描述相同的控制器,兩次) ?

回答

3

使用beforeEach函數創建通用設置。它可以在任何級別添加。

describe('PhoneCat controllers', function() { 
    describe('PhoneListCtrl', function(){ 
    beforeEach(function() { 
     this.scope = {}; 
     this.ctrl = new PhoneListCtrl(scope); 
    }); 

    it('should create "phones" model with 3 phones', function() { 
     expect(this.scope.phones.length).toBe(2); 
    }); 

    it('should create "greetings" models with 3 greeting', funciton(){ 
     expect(this.scope.greetings.length).toBe(3); 
    }); 
    }); 
}); 
0

我知道這個問題很古老,但OP說'這個測試失敗'。不管的foreach()被需要

,算得上是因爲:

expect(scope.phones.length).toBe(2); 

應該是:

expect(scope.phones.length).toBe(**3**); 
+1

測試結果失敗是完全切到OP瞄準來解決這個問題。摩卡用戶使測試失敗*故意*。 OP顯然不會被測試失敗的事實困惑,而是如何避免在測試中重複代碼。 – Louis

+0

@Louis - +1教我一個新單詞。 :-) Tangential - 形容詞 1.屬於或屬於切線的性質;在切線方向上移動或移動。 2.僅僅觸摸;略有連接:切線信息。來自正在考慮的主題的分歧或離題:切向評論。 4.傾向於離題或傾斜回答問題。 – Tracy