简体   繁体   English

AngularJS控制器单元测试 - 注入服务

[英]AngularJS controller unit tests - injecting services

A hopefully simple question about AngularJS unit testing. 一个关于AngularJS单元测试的希望简单的问题。 I have a controller using a simple service (adapted from angular-seed project) 我有一个使用简单服务的控制器(改编自angular-seed项目)

services.js: services.js:

angular.module('myApp.services', []).value('version', '0.1');

controllers.js: 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?! 我无法想象我们如何注入'版本'服务(或创建实例)并将其传递给$ controller()工厂 - 我认为这就是我想要做的事情?! Here's the bare bones spec: 这是裸骨规格:

controllerSpec.js : 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 运行测试工具会产生: > test.sh

... failed (3.00 ms): Error: Error: Unknown provider: versionProvider <- version Error: Unknown provider: versionProvider <- version ...失败(3.00毫秒):错误:错误:未知提供者:versionProvider < - 版本错误:未知提供者:versionProvider < - 版本

I have tried various things with $injector/$provider and module() but to no avail. 我用$ injector / $ provider和module()尝试过各种各样的东西,但无济于事。 I'm sure the answer is simple, but I can't see it. 我确定答案很简单,但我看不出来。

just add beforeEach(module('myApp.services')) to your describe block. 只需将beforeEach(module('myApp.services'))到您的describe块中。 This will load the services module with the "version" service into the test injector and that will make it available to your test. 这将使用“版本”服务将服务模块加载到测试注入器中,这将使其可用于您的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM