The importance of dependencies in functions and testing with Jasmine

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);

Answer №1

After much deliberation, I have come up with a solution. First, I created a mock and added the necessary code to return the user from the getSession function:

beforeEach(inject(function (TestingService, _$httpBackend_, _adminLogStore_, userContext, _ssoMock_) {
    $t = TestingService;
    adminLogStore = _adminLogStore_;
    $httpBackend = _$httpBackend_;
    userContext.userId = uid;
    ssoMock = _ssoMock_;
    ssoMock.getSession.and.returnValue(user);
}

It is important to remember to declare the variable for ssoMock.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Wait for the reaction from react router history to go back

After clicking the submit button in a form, I need to navigate backwards using history.goBack. However, if there is no previous page in the history, I want to redirect to a screen displaying a thank you message using history.replace. const handleSubmit = ( ...

Changing the custom route in React Router to utilize a render prop instead of the component prop

I'm currently working on a React app that incorporates React Router. I've been encountering a bug in my code stemming from my custom ProtectedRoute component: const ProtectedRoute = ({ component, ...args }) => ( <Route component={with ...

Determine the present vertical measurement of the video

I am having trouble determining the actual height of a video element. Despite seeing in the developer tools that it is 384px, I am only able to retrieve a height of 342px. I attempted the following code snippet, but it only gives me the natural height, no ...

The jQuery functions seem to be malfunctioning when trying to retrieve elements by their ids

I'm having trouble with the click function when using IDs, but it works fine with classes. $('#myTab li a').click(function(e) {} When I switch to using classes like this: $('.nav-tabs a.overview').click(function(e) {} it work ...

How can I use JavaScript to find a keyword on a webpage that is not located within an <a> tag or its href attribute?

I'm on a mission to locate a specific keyword within a webpage. Sounds simple, right? Well, here's the tricky part - I need to disregard any instances of this keyword that are nested within an <a> tag. For example: <p>Here is some s ...

Angular does not wait for the backend service call response in tap

Does anyone have a solution for subscribing to responses when the tap operator is used in a service? edit(status) { dataObj.val = status; // call post service with status.. this.service .update(dataObj) .pipe(takeUntil(this._n ...

Tips for properly formatting quotes in JSON to activate a link

I am working with a JSON configuration file that looks like this: "type": "script", "label": "coreapps.archivesRoom.printSelected", "script": "emr.fragmentActionLink(${project.parent.artifactId},\"downloadPatientHistory\", &bs ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Can you explain the meaning of this PHP syntax and why is this variable showing NaN?

Looking for question marks on Google can be quite challenging. Can someone explain this process step by step? $page = isset($_POST['page'])?$_POST['page']:"0"; I believe it means to check if $_POST['page'] is set, use that ...

Preventing Sorting on a Single Item in an AngularJS ui-sortable List

Check out a Plunker example. [updated the plunk based on below answers] Updated Plunk I'm wondering how to disable sorting on specific items, such as item 1 and item 3, so the user cannot move those two items. I attempted to achieve this by using: ...

How to correct header alignment in HTML for Google Table

Utilizing the google visualization table to generate a html table, I have successfully fixed the top section of the html using the stuckpart div. This ensures that regardless of how I scroll, the button remains in place. However, I now aim to fix the table ...

Can you explain the concept of System.register in a JavaScript file?

Can you explain the purpose of System.register in a JS file when utilizing directives in Angular 2? ...

XPages component retrieval function is malfunctioning

Utilizing an XPage with JQuery dialog and client-side validation adds efficiency to the user input process. However, there seems to be a disconnect between the client-side validation and server-side properties. Although the client-side validation functions ...

What are some ways to stop the default event action from occurring when a parent HTML element has an event handler attached to it?

I have a bunch of hyperlinks on my webpage that I want to ajaxify so that clicking on a link deletes the associated item. I attached an event handler to a parent container like this: <div id="parent"> <a href='#' data-itemid='1& ...

Endless loop of jquery textbox focus event

Currently, I am employing jQuery for validating textbox values. I have two textboxes - txt1 and txt2. For this purpose, I have created a jQuery function: $("#txt1").blur(function () { if ($("#txt1").val() == "") { $("#scarrie ...

When trying to publish a new post using postman, the content including the title, message, and image is not displaying

I am currently learning how to build a REST API by following a tutorial. Below is an excerpt from my server.js file: import express from 'express'; import compression from 'compression'; import bodyParser from 'body-parser'; ...

Looking to find a way to identify strings with hyphens in JavaScript?

I am trying to extract specific parts of a URL that follow a certain pattern like the one below: http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath Specifically, I am interested in extracting the portion of the URL that consists of ...

Receiving a 404 error after refreshing the browser in Angularjs routing

I am currently working on a project that involves Angular JS and asp.net web api. Whenever I navigate using this URL http://localhost:3458/Profile An error pops up saying: Description: HTTP 404. The resource you are looking for... However, if I use th ...

Unable to display the column data labels in Highcharts due to the incorrect formatting being presented

I'm having trouble displaying the datetime format at the top of a column in my chart. Although the tooltip shows the correct data when hovering over the columns, the labels are not formatted properly. Received output - 86340000 Expected output - 23: ...

Is there a way to swap out a div with another using ajax and php?

i am looking to update the content from readmore.php into <div id='box'> based on id_pages in index.php after clicking <a class=readmore> Read More </a>. i have been trying to figure out how to retrieve data from readmore.p ...