javascriptangularjsunit-testingangularjs-ngmock

Angularjs ngMock inject before each test or on each test case?


Scenario

I'm currently writing tests for an Angular project, and almost on every article I find, I see them creating "global" variables in a describe block, where they store dependencies to be used in the tests, like this:

describe('Some tests', function() {
    var $controller, $rootScope

    beforeEach(angular.mock.module('myApp'))
    beforeEach(angular.mock.inject(function(_$controller_, _$rootScope_) {
        $controller = _$controller_
        $rootScope  = _$rootScope_
    }))

    it('uses $controller inside', function() {
        // ...
    })
    it('uses $rootScope inside', function() {
        // ...
    })
})

I have found this to be ver DRY since it creates and shares a new instance of a service/factory/etc.. for tests to use. BUT when writing a lot of tests I've noticed that I create globals and then no longer use them, and forget to delete them in the inject() leaving this traces that may cause confusion down the line.

My Confusion

So I have been injecting the dependencies on each test case and then refactor in small describe blocks to globals that don't get out of hand, like this:

describe('Some tests', function() {
    beforeEach(angular.mock.module('myApp'))

    it('uses $controller inside', angular.mock.inject(function($controller) {
        // Test using the $controller
    }))
    it('uses $rootScope inside', angular.mock.inject(function($rootScope) {
        // Test using $rootScope
    }))
})

And this has the added benefit of thing staying local and not having to use variables that have to be searched for where they are coming from, IMHO.

The Question

Is there any problem on injecting dependencies per test instead of inside a beforeEach block?


Solution

  • No there is no such problem you can add dependencies according to your requirement the only problem comes at efficiency, because it has to load same file for multiple times. This problem is not a big deal when writing small amount of test cases but when you start writing more test cases it will slow down eventually. Moreover the module that you are injecting every-time might be dependent on other modules so those modules has to be loaded into memory.That's why it is preferred to use these values as global variables.