View source Improve this doc

angular.mock.inject

API in module ng

Description

NOTE: This function is also published on window for easy access.

The inject function wraps a function into an injectable function. The inject() creates new instance of $injector per test, which is then used for resolving references.

Resolving References (Underscore Wrapping)

Often, we would like to inject a reference once, in a beforeEach() block and reuse this in multiple it() clauses. To be able to do this we must assign the reference to a variable that is declared in the scope of the describe() block. Since we would, most likely, want the variable to have the same name of the reference we have a problem, since the parameter to the inject() function would hide the outer variable.

To help with this, the injected parameters can, optionally, be enclosed with underscores. These are ignored by the injector when the reference name is resolved.

For example, the parameter _myService_ would be resolved as the reference myService. Since it is available in the function body as myService, we can then assign it to a variable defined in an outer scope.

  1. // Defined out reference variable outside
  2. var myService;
  3. // Wrap the parameter in underscores
  4. beforeEach( inject( function(_myService_){
  5. myService = _myService_;
  6. }));
  7. // Use myService in a series of tests.
  8. it('makes use of myService', function() {
  9. myService.doStuff();
  10. });

See also angular.mock.module

Example

Example of what a typical jasmine tests looks like with the inject method.

  1. angular.module('myApplicationModule', [])
  2. .value('mode', 'app')
  3. .value('version', 'v1.0.1');
  4.  
  5.  
  6. describe('MyApp', function() {
  7.  
  8. // You need to load modules that you want to test,
  9. // it loads only the "ng" module by default.
  10. beforeEach(module('myApplicationModule'));
  11.  
  12.  
  13. // inject() is used to inject arguments of all given functions
  14. it('should provide a version', inject(function(mode, version) {
  15. expect(version).toEqual('v1.0.1');
  16. expect(mode).toEqual('app');
  17. }));
  18.  
  19.  
  20. // The inject and module method can also be used inside of the it or beforeEach
  21. it('should override a version and test the new version is injected', function() {
  22. // module() takes functions or strings (module aliases)
  23. module(function($provide) {
  24. $provide.value('version', 'overridden'); // override version here
  25. });
  26.  
  27. inject(function(version) {
  28. expect(version).toEqual('overridden');
  29. });
  30. });
  31. });
  32.  

Usage

  1. angular.mock.inject(fns);

Parameters

ParamTypeDetails
fns…Function any number of functions which will be injected using the injector.