OnResolve
OnResolve

Reputation: 4032

Angular e2e / Karma - Before Suite block?

I know the e2e tests for angular have a beforeEach for individual tests...but I'm looking for a level up for the entire suite. Anyone know a way to run a block of code before the entire test suite is executed?

Upvotes: 2

Views: 1179

Answers (2)

tarrball
tarrball

Reputation: 2298

I needed to do this to run a bunch of tests that required a user be logged in, so I created a file karma.suiteInitialize.js with the following code:

(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");
    }
})();

and then just added it to karma.config.js immediately after the app files like:

    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'
    ]

..and that was all it took. This doesn't reduce the number of calls to log the user in (it still happens for every test), but it does make it convenient.

Upvotes: 3

lorcan
lorcan

Reputation: 3300

If you don't mind the block being run for every test in your suite you could nest your tests and have a beforeEach at the highest level, e.g.,

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.
    });
});

However, the main beforeEach will execute before every it block in the entire suite. If you want the code to be executed only once then this isn't the solution for you.

Upvotes: 1

Related Questions