Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I inject dependencies into AngularJS controller tests without using Jasmine-specific inject()
    primarykey
    data
    text
    <p>I'm trying to wrap my brain around dependency injection in AngularJS. Let's say this is my very exciting application code:</p> <pre class="lang-js prettyprint-override"><code>function PrideRockCtrl($scope, King) { $scope.king = King; } angular.module('Characters', ['ngResource']) .factory('King', function() { return "Mufasa"; }); </code></pre> <p>I want to test <code>PrideRockCtrl</code>. If I follow examples in the documentation and in the tutorial, I could use the <code>module('Characters')</code> to configure the injector and use <code>inject()</code> to get some dependencies. i.e.:</p> <pre class="lang-js prettyprint-override"><code>describe('Pride Rock', function() { beforeEach(module('Characters')); it('should be ruled by Simba', inject(function($rootScope, $controller) { var scope = $rootScope.$new(); var ctrl = $controller(PrideRockCtrl, {$scope: scope}); expect(scope.king).toEqual("Mufasa"); })); }); </code></pre> <p>This works fine, but this isn't a cross-test-framework solution. The <code>module()</code> and <code>inject()</code> test helpers are only compatible with Jasmine. </p> <h3>What's the best way to manually accomplish the same dependency injection without using <code>module()</code> or <code>inject()</code>?</h3> <p>I came up with this:</p> <pre class="lang-js prettyprint-override"><code>describe('Pride Rock', function() { it('should be ruled by Mufasa', function() { var $injector = angular.injector(['Characters']); var $controller = $injector.get('$controller'); var scope = $injector.get('$rootScope').$new(); var king = $injector.get('King'); var ctrl = $controller(PrideRockCtrl, {$scope: scope, King: king}); expect(scope.king).toEqual("Mufasa"); }); }); </code></pre> <p>This seems very verbose. Is there a better way?</p> <p>jsFiddle: <a href="http://jsfiddle.net/johnlindquist/d63Y3/" rel="nofollow">http://jsfiddle.net/johnlindquist/d63Y3/</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload