Angularjs茉莉测试时注入控制器空 [英] Angularjs injected controller empty when testing with Jasmine
问题描述
我目前正在与角度和使用因果报应和茉莉花努力使测试。该过滤器,例如被注入主模块,可以没有任何问题进行测试,但是当我尝试测试控制器我接受注射后的空对象。
I am currently working with Angular and using Karma and Jasmine to make the testing. The filters, for example are injected to the main module and can be tested without any problem, but when I try to test the controllers I get an empty object after the injection.
下面是我的主要模块的code:
Here is the code of my main module:
(function () {
'use strict';
var dependencies = [];
angular.module('myApp', dependencies)
}());
我是测试控制器:
The controller that I am to test:
(function () {
'use strict';
angular.module('myApp')
.controller('NavCtrl', ['$scope',
function ($scope) {
$scope.currentUser = null;
}]);
}());
和最后的测试套件:
describe ("controller", function() {
beforeEach(module("myApp"));
var $scope, $rootScope, controllerLoader;
beforeEach(inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
var $controller = $injector.get('$controller');
controllerLoader = function() {
return $controller('NavCtrl', {
'$scope': $scope
});
};
}));
it ("testing injection", function() {
var controller = controllerLoader();
expect(controller).toNotEqual({});
})
});
但是测试的结果为失败,和调试我看到注入的控制器是空的了。我已经尝试给一个假名控制器和测试刚刚崩溃,拿什么控制器侦测到但出于某种原因,我没有得到它的属性。
But the result of the test is FAIL, and after debugging I see that the injected controller is empty. I have already tried to give a false name for the controller and the test just crashes, what means that the controller is detected but for any reason I am not getting its properties.
推荐答案
我有一个类似的问题。所不同的是,在我的应用我使用RequireJS,所以有些部分是有点不同,但我想总可以帮助你。
I was having a similar issue. The difference is that in my application I am using RequireJS, so some parts are a little different, but I guess the overall might help you.
我修改它以符合您的名字:
I modified it to match your names:
define(['app/app.module', 'angular', 'angular-mocks'], function () {
describe('Controller Unit test', function () {
var $controller;
beforeEach(module('myApp'));
beforeEach(inject(function (_$controller_) {
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
}));
describe('Get the controller', function () {
it('should contain controller', function () {
var $scope = {};
var controller = $controller('NavCtrl', {$scope: $scope});
console.log(controller);
expect(controller).toBeDefined();
});
});
});
});
这是加载两个角和角嘲笑非常重要的。 不过,我认为主要的问题是,你的 controllerLoader
功能在 beforeEach
部分。注射在测试本身的描述
部分作出。
It is very important to load both angular and angular-mocks. However I think the main issue is that your controllerLoader
function is in beforeEach
section. The injection has to be made in the describe
section of the test itself.
这篇关于Angularjs茉莉测试时注入控制器空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!