Reputation: 22747
This is my 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;
});
};
}]);
and this is my 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);
});
});
When I test the code by doing karma start
, it raises this error:
Expected undefined to be 'y'.
at Object.<anonymous> (/home/a/Documents/CMS/CMSApp/static/js/karma/tests/test_sp.js:53:38)
and points to the line:
expect(ctrl.cerrorMessages).toBe(mockBaseService.cerrorMessages);
How vome it is saying that ctrl.cerrorMessages
is undefined even though, right after ctrl.add()
is executed, it gets defined in the callback of BaseService.add.sp()
like so:
self.cerrorMessages = BaseService.cerrorMessages;
? I tried initializing the variable at the start of the controller like so:
self.cerrorMessages;
but that also didn't work (same error was raised).
Upvotes: 0
Views: 1444
Reputation: 6054
You probably want to call through so that actual method is called
spyOn(mockBaseService.add, 'sp').and.callThrough();
Upvotes: 2