AngularJS控制器单元测试 - 注射服务 [英] AngularJS controller unit tests - injecting services

查看:140
本文介绍了AngularJS控制器单元测试 - 注射服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关AngularJS单元测试希望简单的问题。我用一个简单的服务(改编自角种子工程)控制器

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"];

这伟大工程的IM我的应用程序。不过,我有麻烦创建单元测试框架的工作控制器。我想不出我们如何注入'版本'服务(或创建实例),并把它传递给$控制器()工厂 - 我认为这就是我想做的事情?下面是裸露的骨头规格:

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');
});

运行测试工具收益率:
> test.sh

...失败(3.00毫秒):错误:错误:未知提供商:versionProvider&LT; - 版本
            错误:未知提供商:versionProvider&LT; - 版本

我曾尝试与喷油$ / $提供商和模块(),但无济于事各种事情。我敢肯定的答案很简单,但我无法看到它。

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.

推荐答案

只是添加 beforeEach(模块('myApp.services'))来形容你的块。这将与版服务加载服务模块插入测试喷油器,并且将其提供给您的测试。

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.

这篇关于AngularJS控制器单元测试 - 注射服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆