![](/img/trans.png)
[英]One Angular Controller Karma-Jasmine test works, but not another one
[英]Jasmine + karma + angular test create controller
我在哪里犯错? 如何在Jasmine + angular中获取控制器实例? 如何解决控制器? 我不知道该用什么解决。
'use strict';
angular.module('myApp.contact', ['ui.router'])
.controller('contactCtrl', ['$scope', function ($scope) {
$scope.contact = {
name: 'John Doe'
};
}]);
describe('myApp.contact module tests', function () {
var scope, createController;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
createController = function () {
return $controller('contactCtrl', {
'$scope': scope
});
};
}));
it('contact name is John Doe', function () {
var controller = createController();
expect(controller).toEqual('John Doe');
});
});
myApp.contact module tests
✗ contact name is John Doe
Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined
http://errors.angularjs.org/1.4.9/ng/areq?p0=contactCtrl&p1=not%20a%20function%2C%20got%20undefined
at E:/angular-seed/app/bower_components/angular/angular.js:68:12
at assertArg (E:/angular-seed/app/bower_components/angular/angular.js:1816:11)
at assertArgFn (E:/angular-seed/app/bower_components/angular/angular.js:1826:3)
你在这里错过了几件事
module('myApp.contact')
之前执行module('myApp.contact')
来初始化angular模块,以使控制器和所有其他组件可用,以使Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined
离开了。 scope
对象而不是controller
(当属性绑定到this
时可以使用controller) 不要忘记在页面上引用contactCtrl.js
和ui-router.js
。
expect(scope.contact.name).toEqual('John Doe');
码
describe('myApp.contact module tests', function () {
var scope, createController;
beforeEach(module('myApp.contact')); //1st change
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
createController = function () {
return $controller('contactCtrl', {
'$scope': scope
});
};
}));
it('contact name is John Doe', function () {
var controller = createController();
expect(scope.contact.name).toEqual('John Doe'); //2nd change
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.