Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS controller unit tests - injecting services

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.

like image 570
iceberg Avatar asked May 11 '12 13:05

iceberg


People also ask

Is AngularJS code unit testable?

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.

What is controller inject in AngularJS?

Injecting a value into an AngularJS controller function is done simply by adding a parameter with the same name as the value (the first parameter passed to the value() function when the value is defined).

Why we use $inject in AngularJS?

It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable. AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.


1 Answers

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.

like image 124
Igor Minar Avatar answered Sep 23 '22 04:09

Igor Minar