Current Situation
As I work on writing tests for an Angular project, I have come across a common practice of creating "global" variables in a describe block to store dependencies needed for the tests. This approach involves defining variables like $controller and $rootScope within the describe block and then using them in the individual test cases.
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() {
// ...
})
})
While this method is efficient in terms of reusing dependencies across multiple tests, I have noticed that it can lead to unused global variables piling up and potentially causing confusion if not properly managed.
Proposed Solution
To address this issue, I have started injecting dependencies directly into each test case instead of relying on globals defined in a beforeEach block. By doing so, I can keep the scope of dependencies local to the specific test and avoid cluttering the code with unnecessary global variables.
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
}))
})
This approach not only helps maintain code cleanliness but also simplifies the process of tracking where dependencies are coming from.
The Query
Given the above context, is there any drawback to injecting dependencies per test rather than within a beforeEach block?