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?