Unit testing AngularJS service with promise

Could use some assistance with unit testing a service that relies on a repository returning a promise to the consumer.
Struggling to figure out how to properly test the promise. Any guidance would be welcomed!

Answer №1

Here is a sample test using $httpBackend for mocking a service.

var describe = window.describe,
    beforeEach = window.beforeEach,
    afterEach = window.afterEach,
    it = window.it,
    expect = window.expect,
    inject = window.inject,
    module = window.module,
    angular = window.angular,
    serviceURL = '/' + Techsson.Core.Global.Language + '/api/sessionlimit/getdata',
    $scope,
    sessionLimitServiceResponse;

describe('Jasmine - SessionLimitService', function () {

    beforeEach(module('sessionlimit.module'));

    var sessionLimitServiceMock, q;

    beforeEach(inject(function (_SessionLimitService_, _SessionLimitResository_, $httpBackend, $rootScope) {
        sessionLimitServiceMock = _SessionLimitService_;
//avoiding the use of global variables
    $httpBackend.when('GET', serviceURL)
                            .respond('foo', {/*Headers*/});
        }));

    it("Content array should be empty", function () {
        expect(sessionLimitServiceMock.content.length).toEqual(0);
    });

    it('Content array should contain a value', function() {
        $httpBackend.expectGET(serviceURL);
        sessionLimitServiceMock.getData().then(function(value) {
            expect(value).toEqual('foo'); // NO CHANGE OCCURS
        });
        $httpBackend.flush();
        });
    });

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

Gradient on multiple faces in Three.js

I'm currently struggling with creating an HSV cylinder using three.js. I am facing difficulties in properly mapping the gradient to the faces of the cylinder. Initially, I attempted to create my object in this manner: https://i.sstatic.net/WboAE.png ...

Learning to retrieve specific properties from an event target in JavaScript

Here is the code snippet I am working with: <h1 msgId = "someId"> Some text </h1> And in my code.js file, I have the following function: document.addEventListener('click', function(e) { target = e.target; }, false); I am tryin ...

What is the best way to retrieve the value from local storage?

const value = document.getElementById("demo").getAttribute('value'); if(typeof(Storage)!=="undefined") { alert(value); localStorage.setItem("GetData", value); alert(localStorage.getItem("GetData")); } function loading() { alert("coming" ...

Conceal the item and reveal it upon clicking

There are three div boxes included in a rotator script. However, when clicking on the right button, all three boxes appear overlapping each other instead of showing one at a time. How can I make it so that only one box is shown and the others appear upon c ...

React - Attempting to access property X from an undefined variable

Trying to access the string in section1.text, but my console is showing: https://i.stack.imgur.com/ox8VD.png Here's the JSX code I'm using: return ( <div> <h1>{this.props.article.title}</h1> ...

Using ReactJS and JavaScript to transform an array into a fresh array

I am working with an array that looks like this: var oldArray = [ {number: '12345', alphabet: 'abcde'}, {number: '54321', alphabet: 'abcde'}, {number: '67891', alphabet: 'abcde'}, ...

Database hosted on Heroku platform

Curious to know, if you utilize Heroku for hosting, what database do you prefer? Do you lean towards PostgreSql, MongoDB, or another option altogether? I initially developed a bot using sqlite3, but quickly discovered that Heroku does not support it and ...

What is the method to spin an item in three js while keeping its axis in focus?

Looking to rotate a globe object around its y-axis smoothly? I have come across a helpful function for achieving this: function rotateAroundObjectAxis(object, axis, radians) { var rotationMatrix = new THREE.Matrix4(); rotationMatrix.makeRotationAxis ...

Enhance your WordPress menu with additional attributes

Currently, I am implementing a lightweight lightbox script on my WordPress website. My goal is to have one of the main navigation buttons open a Vimeo link in the lightbox. According to the lightbox documentation, I need to "Add the 'data-lity' a ...

Importing Laravel select2 library is necessary for enhancing user experience and improving

I've been attempting to incorporate select2 into my project without success. Every time I try these two methods, I always receive an error saying $('#state').select2 is not a function. However, when I include select2 in a standard <scrip ...

If an iframe contains a div with a particular class inside, then execute the following code

I need to dynamically add a class to the parent element if a specific class is present in its child. The issue: the content is within an iFrame and I'm not very proficient with jQuery. It doesn't necessarily have to be jQuery, any alternative m ...

React - The previous condition is maintained when selected

A few days back, I encountered a perplexing issue and sought help by posting a question regarding obtaining an index of values. To my relief, I received a reliable answer that enabled me to successfully tweak my existing code. One problem that arose was w ...

AJAX request stops functioning once the page is reloaded

As a beginner in JavaScript, I am facing an issue with my AJAX call. I have set up the call to process a back-end function when a button is clicked and expect to receive a response once the function is completed. However, whenever I refresh the page whil ...

Adjusting the size of HighCharts HighMaps with a custom function

Simple query here (I believe) I have a DIV with the class "container" acting as my Map. The Highcharts plugin I'm using is responsive, but it only resizes when the window does. I'm looking to manually trigger a resize without adjusting my windo ...

Submitting a Form with Multiple Pages

I'm encountering a challenge that I'm struggling to work through. Initially, we had a professional build our website, but since parting ways with the company, I've taken over site management. While I can handle basic tasks, I lack the expert ...

Difficulty persisting when removing accents/diacritics from a string in Angular with IE 11

When attempting to utilize the String.normalize("NFD").replace(/[\u0300-\u036f]/g, "") method, I encountered an issue in IE11. ERROR TypeError: The object does not support the property or method "normalize" ...

Issue with Redux saga not responding to action initiated by clicking on an icon

Declaration of Saga function* DoStuffInSaga({myRef}){ try { console.info("saga running"); return yield delay(1000, 1); } catch(error){ console.warn(error); } } export function* mySaga(){ yield all([ yi ...

Sign-in options displayed in a drop-down menu

I have successfully implemented a jQuery animation for a dropdown sign in div. The sign up form is integrated with PHP to verify the existence of users in the database. However, I came across an issue where if I echo something, the dropdown menu disappears ...

Preflight response indicates that the Access-Control-Allow-Methods does not permit the use of the PATCH method

Implementing the axios PATCH method in my ReactJS project to update a record is resulting in a failure with the following error message: Failed to load : Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response. Below is the co ...

Connecting a Date object by using :value and @input within a VueJS component

Successfully linking a date form input with a date object using :value and @input instead of v-model as outlined in this method has been a great ongoing experience. It allows for displaying and modifying the date in the form input, as well as saving the up ...