Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/10551986/angularjs-controller-unit-tests-injecting-services

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...