In troubleshooting my AngularJS Service and Jasmine test, I encountered an issue. I am using service dependency within another service, and when attempting to perform a Unit Test, an error is thrown:
TypeError: undefined is not an object (evaluating sso.getSession().userId')
The main service 'sso' contains a function to retrieve Session data which includes userId and email:
myApp.service('sso', function($rootScope) {
var session;
function initSession(){
....
someData = .....;
session = someData;
}
function getSession() {
return session;
}
})
There is also another service where I utilize the functions from the 'sso' service along with 'userContext' without any issues:
myApp.service('adminLogStore', function($http, userContext, sso) {
var self = this;
this.saveLog = function(log, userContext.userId) {
return .........
}
var admin = {
id: sso.getSession().userId,
email: sso.getSession().userEmail,
login: sso.getSession().username
};
.......
}
Lastly, here is the unit test that I have implemented:
describe('Service count ', function () {
var $t, $httpBackend, adminLogStore;
var uid = 5;
beforeEach(ModuleBuilder.forModules('myapp.common', 'testing.helpers')
.serviceWithMocksExcept('adminLogStore', '$rootScope', '$http', '$q', '$location')
.build()
);
beforeEach(inject(function (TestingService, _$httpBackend_, _adminLogStore_, userContext, sso) {
$t = TestingService;
adminLogStore = _adminLogStore_;
$httpBackend = _$httpBackend_;
userContext.userId = uid;
}));
it('good value', inject(function () {
expect(userContext.userId).toBe(5);
}));
});
I need guidance on how to correctly mock the 'sso' function. The error occurs when trying to access .userId after calling sso.getSession().
I attempted to add a mock within the beforeEach block right below userContext.userId assignment, but it did not solve the issue:
var user = {
userId: 5,
userEmail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b5a4c4b7f500d114f53">[email protected]</a>',
username: 'test'
};
sso = jasmine.createSpyObj('sso', ['getSession']);
sso.getSession = function() {
return user;
};
--- EDIT
I tried mocking the 'admin' object instead of the 'sso' object, but the issue persists.
var user = {
id: 5,
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffbeafcfbcfe0bda1ffe3">[email protected]</a>',
login: 'test'
};
beforeEach(inject(function (TestingService, _$httpBackend_, _adminLogStore_, userContext) {
$t = TestingService;
adminLogStore = _adminLogStore_;
$httpBackend = _$httpBackend_;
userContext.userId = uid;
adminLogStore.admin = user;
}
and I made changes in the adminLogStore service as follows:
this.admin = {
// id: 12,
id: sso.getSession().userId,
email: sso.getSession().userEmail,
login: sso.getSession().username
};
Yet, the same error persists.
--- Edit 2
I also attempted to mock sso.getSession() in this manner, but it did not resolve the issue:
spyOn(sso, "getSession").and.returnValue(user);