【发布时间】:2015-07-03 19:12:36
【问题描述】:
我在 AngularJS 控制器中定义了一个在初始化时调用的方法。我想使用 Jasmine ("jasmine-core": "^2.3.4", "karma": "^0.12.37") 对其进行测试。我关注互联网上的一些教程和 StackOverflow 问题,但我找不到正确的答案。请看一下这段代码:
控制器usersAddUserController:
(function () {
'use strict';
angular.module('app.users.addUser')
.controller('usersAddUserController', ['$scope', 'usersAddUserService', function ($scope, usersAddUserService) {
usersAddUserService.getCountryPhoneCodes().then(function (phoneCodes) {
$scope.phoneCodes = phoneCodes;
});
}]);
}());
茉莉花测试:
(function () {
'use strict';
describe('usersAddUserControllerUnitTest', function () {
var scope, deferred, objectUnderTest, mockedAddUserService;
beforeEach(module('app'));
beforeEach(inject(function ($rootScope, $q, $controller) {
scope = $rootScope.$new();
function emptyPromise() {
deferred = $q.defer();
return deferred.promise;
}
mockedAddUserService = {
getCountryPhoneCodes: emptyPromise
};
objectUnderTest = $controller('usersAddUserController', {
$scope: scope,
usersAddUserService: mockedAddUserService
});
}));
it('should call getCountryPhoneCodes method on init', function () {
//when
spyOn(mockedAddUserService, 'getCountryPhoneCodes').and.callThrough();
deferred.resolve();
scope.$root.$digest();
//then
expect(mockedAddUserService.getCountryPhoneCodes).toHaveBeenCalled();
});
});
}());
运行测试后,错误信息是:
PhantomJS 1.9.8 (Windows 7 0.0.0) usersAddUserControllerUnitTest 应该在 init FAILED 上调用 getCountryPhoneCodes 方法
Expected spy getCountryPhoneCodes to have been called.
我显然错过了一些东西,但我无法弄清楚它是什么。任何帮助将不胜感激。
【问题讨论】:
标签: javascript angularjs karma-jasmine