回答

1

如果你不介意的塊是運行在你的浴室你可以窩每一個測試你的測試,並有beforeEach在最高水平,例如,

describe("Entire Suite", function() { 

    beforeEach(function(){ 
    // Executed for every it in the entire suite 
    }); 

    it('Test', function() { 
    // Only the first beforeEach will be called prior to this test. 
    }); 

    describe("Subset Suite", function(){ 

    beforeEach(function(){ 
     // Executed for every it in this subset suite 
    }); 

    it('Subtest', function() { 
     // Both beforeEach blocks will have been called prior to this test. 
    }); 
}); 

然而,主要beforeEach將執行之前它在整個套件中阻塞。如果你想讓代碼只執行一次,那麼這不是你的解決方案。

3

我需要做的這個運行了一堆,需要一個用戶登錄的測試,所以我創建了一個文件karma.suiteInitialize.js用下面的代碼:

(function() { 
    'use strict'; 

    angular 
     .module("app") 
     .run(testInitialize); 

    testInitialize.$inject = ['userService']; 

    function testInitialize(userService) { 
     userService.setUser({ UserName: 'Test user'}); 
     // if (userService.isLogged()) 
     //  console.log("Test user logged in"); 
    } 
})(); 

,然後只將它添加到karma.config.js後立即應用程序文件如:

files: [ 
     '../Scripts/angular.js', 
     '../Scripts/angular-mocks.js', 
     '../Scripts/angular-route.js', 
     '../Scripts/angular-filter.js', 
     '../Scripts/angular-resource.js', 
     '../Scripts/angular-scroll.min.js', 
     'app/app.module.js', 
     'app/**/*.js', 
     'karma.suiteInitialize.js', 
     'tests/**/*.js', 
     'app/**/*.html' 
    ] 

..而這一切都花了。這不會減少登錄用戶的呼叫數量(它仍然會發生在每個測試中),但它確實使其變得方便。