我第一次尝试在AngularJS中统一一个控制器。我想测试这个控制器中的登录函数是否调用了正确的服务,但是我得到了一个错误,即控制器中不存在这个函数。我做错什么了?我还要嘲笑更多吗?但是,我不应该模拟要测试的控制器中的函数,因为如果我这样做,那么整个测试将是毫无意义的,还是我错了?
控制器-片段:
function LoginController($scope, $state, myService, ngToast) {
$scope.loginUser = loginUser;
activate();
function activate() {}
function loginUser(credentials) {
myService.authenticate(/*things*/);
}
}测试-代码:
describe('Login Controller', function () {
'use strict';
//globals
var controller, scope;
var $controller, $state, myService, ngToast;
//needed modules
beforeEach(module('app.login'));
beforeEach(module('app.core'));
beforeEach(module('ui.router'));
//instanciate Controller
beforeEach(inject(function (_$controller_, _$state_, _myService_, _ngToast_) {
scope = {};
$state = _$state_;
myService = _myService_;
ngToast = _ngToast_;
$controller = _$controller_;
controller = $controller('LoginCtrl', {
$scope: scope,
$state: $state,
myService: myService,
ngToast: ngToast
});
}));
it('should have an existing controller', function () {
expect(controller).toBeDefined();
});
/*************************** unit-tests ***************************/
describe('.loginUser()', function () {
it('should exist', function () {
expect(controller.loginUser).toBeDefined();
});
});
});我在运行业力时遇到的错误是:
.loginUser()
✗ should exist
TypeError: controller.loginUser is not a function
at Object.<anonymous> (src/login/login.controller.spec.js:74:31)但在我看来,控制器确实存在,因为这个测试没有失败:
Login Controller
✓ should have an existing controller发布于 2017-01-11 17:34:00
这是因为loginUser是在$scope上定义的,而不是在控制器上定义的,所以loginUser没有绑定到测试中的控制器对象。
要测试loginUser,请执行以下操作:
如果您想在控制器本身上测试loginUser,那么可以使用控制器作为语法,设置this.loginUser = loginUser,而不是$scope.loginUser = loginUser。然后,您将能够在测试中使用controller.loginUser。
https://stackoverflow.com/questions/41596455
复制相似问题