AngularJS controller unit tests - injecting services

angularjs, unit-testing

Solution

just add `beforeEach(module('myApp.services'))` to your describe block. This will load the services module with the "version" service into the test injector and that will make it available to your test.

Problem

A hopefully simple question about AngularJS unit testing. I have a controller using a simple service (adapted from angular-seed project) services.js: ``` angular.module('myApp.services', []).value('version', '0.1'); ``` controllers.js: ``` function MyCtrl1($s, version) { $s.version = version; } MyCtrl1.$inject = ["$scope","version"]; ``` This works great im my app. However, I have trouble creating the controller in unit test frame work. I can't figure our how to inject 'version' service (or create instance) and pass it to $controller() factory - I assume that's what I want to do?! Here's the bare bones spec: controllerSpec.js: ``` beforeEach(inject(function($rootScope, $controller) { scope = $rootScope.$new(); // how about version service? ctrl = $controller(MyCtrl1, {$scope: scope, /* version: <where from?> */}); })); it('Version should be 0.1 ...', function() { expect(scope.version).toBe('0.1'); }); ``` Running the test harness yields: >test.sh ... failed (3.00 ms): Error: Error: Unknown provider: versionProvider <- version Error: Unknown provider: versionProvider <- version I have tried various things with $injector/$provider and module() but to no avail. I'm sure the answer is simple, but I can't see it.

Original source