36

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.

0

1 Answer 1

56

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! That was simple. It didn't occur to me having two beforeEach() calls - interesting.
By the way, is it a good practice to write unit tests for a controller with a service dependency ? Or it is better to create the mock for the service, and then write one test for the controller and one for the service ?
@e.gluhotorenko I find it easier to do the second option, test the controllers using a mock service. Then test the services separately. I found Tim Buschtöns article about how to use mocks in Jasmine really helpful. Made setting up mocks for services easy and overall my tests more flexible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.