这是我的sp.js
:
angular.module("SpPageApp", ["BaseApp"])
.controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
var self = this;
self.add = function() {
BaseService.add.sp(self.sp, function() {
self.cerrorMessages = BaseService.cerrorMessages;
});
};
}]);
这是我的test_sp.js
:
describe('Controller: MainCtrl', function() {
var ctrl, mockBaseService;
beforeEach(function() {
mockBaseService = {
spls: 'x',
cerrorMessages: 'y',
add: { sp: function(something, cb) { cb() } },
fetch: { selfsps: function(cb) { cb() } },
logout: function() {},
};
module('BaseApp', function($provide) {
$provide.value('BaseService', mockBaseService);
});
module('SpPageApp');
inject(function($controller) {
ctrl = $controller('MainCtrl', {
});
});
});
it('add() calls through to BaseService.add.sp.', function() {
ctrl.sp = "{'spName': 'test post'}"
spyOn(mockBaseService.add, 'sp');
ctrl.add();
expect(mockBaseService.add.sp).toHaveBeenCalledWith(ctrl.sp, jasmine.any(Function));
expect(ctrl.cerrorMessages).toBe(mockBaseService.cerrorMessages);
});
});
当我通过karma start
测试代码时,会引发此错误:
Expected undefined to be 'y'.
at Object.<anonymous> (/home/a/Documents/CMS/CMSApp/static/js/karma/tests/test_sp.js:53:38)
并指向该行:
expect(ctrl.cerrorMessages).toBe(mockBaseService.cerrorMessages);
vome如何说ctrl.cerrorMessages
未定义,即使在执行ctrl.add()
之后,它在BaseService.add.sp()
的回调中定义如下:
self.cerrorMessages = BaseService.cerrorMessages;
?我尝试在控制器的开头初始化变量,如下所示:
self.cerrorMessages;
但这也没有奏效(引发同样的错误)。
答案 0 :(得分:2)
您可能希望通过调用来调用实际方法
spyOn(mockBaseService.add, 'sp').and.callThrough();