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

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

问题描述

一个关于 AngularJS 单元测试的简单问题.我有一个使用简单服务的控制器(改编自 angular-seed 项目)

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

这在我的应用中效果很好.但是,我无法在单元测试框架工作中创建控制器.我无法弄清楚如何注入版本"服务(或创建实例)并将其传递给 $controller() 工厂 - 我认为这就是我想要做的?!这是裸骨规范:

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 <- 版本错误:未知提供者:versionProvider <- version

我用 $injector/$provider 和 module() 尝试了各种方法,但都无济于事.我确定答案很简单,但我看不到.

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(module('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天全站免登陆