Karma - Monitoring Function Error Management

I have a similar service setup:

app.service('usersService.v2', ['$http', '$q', '$exceptionHandler', 'User', 'userValidator.v2', 'CRUD', function($http, $q, $exceptionHandler, User, userValidator, CRUD){
    function dummyPromise(){
        var dummyDeferred = $q.defer();
        dummyDeferred.resolve('dummy');

        return deferred.promise;
    }

    this.getUser = function(userID, companyID){
        try{
            userValidator.validateId(userID);
            userValidator.validateId(companyID);
        }
        catch(e){
            $exceptionHandler(e);
            return dummyPromise();
        }

        return $http.get(apiUrl + 'api/v2/companies/' + companyID + '/users/' + userID)
            .then(function(response){
                var user = new User(response.data);

                try{
                    userValidator.validateUser(CRUD.READ, user);
                }
                catch(e){
                    $exceptionHandler(e);
                    return;
                }

                return user;
            })
    };
}]);

I'm interested in testing the service's behavior based on the validation functions performed by userValidator.*. These functions contain if/else blocks that throw errors.

In Karma, my test script looks like this:

describe('Service: usersService.v2', function () {
    var usersService, httpBackend, state, userValidator;
    const url = 'address'

    function _inject() {
        angular.mock.inject(function ($injector) {
            usersService = $injector.get('usersService.v2');
            userValidator = $injector.get('userValidator.v2');
            httpBackend = $injector.get('$httpBackend');
        });
    }

    beforeEach(function () {
        angular.mock.module('app');
        _inject();
    });

    describe('getUser', function () {
        beforeEach(function () {
            httpBackend.when('GET', url);
        });
        afterEach(function () {
            httpBackend.verifyNoOutstandingExpectation();
            httpBackend.verifyNoOutstandingRequest();
        });

    it('should return a dummy promise if ID validation fails', function(){
            spyOn(userValidator, 'validateId').and.throwError('Missing or incorrect ID');
            usersService.getUser()
                 .then(function(data){expect(data).toBe('dummy');})
        });
    );
})

However, when I run the tests with Karma, an error occurs. It seems like the catch block used to handle exceptions is not executing properly. What could be the issue here?

Thanks, Manuel


UPDATE: The validate methods look something like this:

... code code code ...
this.validateId = function(ID){
    if(!ID || !angular.isNumber(ID)) throw 'Missing or incorrect ID';
}

The problem arises because Karma is attempting to handle the error thrown by validation itself instead of allowing the userService to manage it.

Answer №1

You are currently running tests on the usersService.v2. While testing this service, keep in mind that you cannot simultaneously test the userValidator.v2. However, it is possible to create a mock of the userValidator.v2 service.

var userValidator;

beforeEach(function() {

    module(function($provider) {
        userValidator = {
            validateId: function(id) {

                if (id === 123 || id === 456 ) { //set your mock test IDs here for successful validation
                    return true;
                }

                return false;
            }
        };

        $provider.value('userValidator.v2', userValidator);
    });
});

describe('getUser', function () {

        beforeEach(function () {
            httpBackend.when('GET', url)
            .respond(200, {
                    data: "dummy"
                });
        }); 

    it('should provide a dummy promise if the ID validation fails', function() {

        usersService.getUser(9879, 8798) // This is the scenario where the validation FAILS
            .then(function(data) { expect(data).toBe('dummy'); });

    });
});

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

Pressing a button will reset the input spinner in Bootstrap

Is there a way to reset the bootstrap input spinner by clicking a button? I attempted using document.getelementbyId().value = "0" and also tried using reset(), but neither method worked. Any suggestions on how to successfully reset it? function resetScor ...

A guide on updating the values of an array of objects using a different array

As a newcomer to the world of JS, I hope you can bear with me if my question seems complex and possibly repetitive. This issue has been bothering me for quite some time now without finding a satisfactory answer or solution. I have an array of Objects wher ...

Looping through a JSON object in Highcharts to populate data series

I'm brand new to Java Script and I'm on a mission to loop through my JSON object and populate the Highcharts data series. You can take a look at my static demonstration of what I'm trying to achieve on JS Fiddle. Check out JsFiddle here Any ...

Undefined property error

router.post('/:token',(req,res)=>{ let language= req.query.language let name= req.query.name let param =[] if(req.path.length == 5){ param.push({ language: language },{ name: name }) ddp.personConnected(param, function(err, response) { i ...

Bring in the content to Notepad utilizing jQuery

How can I export data to Notepad? I have fields for Name, Age, and WorkingStatus that are input as text and textarea. Is there a demo or code available to help me insert this data into Notepad? ...

"Underscores in an array of primary keys serve as markers for

I want to filter a list of objects using underscore based on their primary key being included in a specific array of primary keys. list = [object{pk: 1}, object{pk: 2}, object{pk: 3}] primary_key_list = [1,2] The desired outcome is to return [object{pk: ...

Looking to leverage iframes in your Javascript code?

Currently, I am implementing a JSP popup window using JavaScript with an iframe to display a table of multiple records. However, when I disable the table of multiple records, it does not prevent the onclick function (hyperlink). The code snippet is provid ...

fill out an HTML form and send it in

When submitting a form with two components, only the first form 'School' and the submit button itself are successfully submitted. The second form 'pool' seems to disappear somehow. <form method='get'> <select nam ...

Uncovering the origin of surprising reactivity issues in Vue 3 component workings

In my current project, I'm working on a basic Vue-3 app and encountering an issue that's puzzling me. The view in question is rendered through the router and consists of simple state components - an object reference for storing text field values ...

Tips for locating numerous div IDs within JavaScript snippets

In my Bootstrap 4 project, I came across a helpful solution on Stack Overflow for creating a dropdown accordion style using JavaScript (Twitter Bootstrap: How to create a dropdown button with an accordion inside it?). I customized the script for my website ...

Maintain original pitch of HTML video content (preservesPitch, mozPreservesPitch, webkitPreservesPitch)

I am attempting to turn off the preservesPitch feature on a video element that is playing in slow motion by adjusting the video's playbackRate. In Chrome, video.webkitPreservesPitch is not defined, and changing it to false or true doesn't affect ...

Console does not display Jsonp returned by ajax request

I'm trying to fetch data from an external page on a different domain using the following code: var instagram_container = $('div#instagram-answer'); if (instagram_container.length>0) { var url = 'http://www.xxxx.it/admin/get_inst ...

Proceed with the execution of the script after a successful completion of the jQuery AJAX request

I am facing a challenge with my click function that needs to open a popup window once the ajax call is successful. I have tried different solutions like setting async: false, placing the popup in the ajax call (which got blocked by the browser), and using ...

Using Ajax and jQuery to fetch a record after submitting a form

I have a form that uses Ajax/jQuery to submit data to a database. The form is handled by a PHP script and successfully stores the information in MySQL. However, I want to display the submitted values on the page after submission. Although I am new to this ...

Incorporating a JavaScript file into Angular

I'm looking to incorporate a new feature from this library on GitHub into my Angular project, which will enhance my ChartJS graph. @ViewChild('myChart') myChart: ElementRef; myChartBis: Chart; .... .... const ctx = this.myChart.nativeEleme ...

Dynamic property access using optional chaining in JavaScript

My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid. export const theme = { headers: { h1: { }, h6: { color: '#828286' }, }, } console.in ...

Encountered an Unhandled Rejection error in react-planner when utilizing threejs: TypeError - url.lastIndexOf function is not recognized

Incorporating react-planner into my React application, I am utilizing a collection of 3D items that are stored in a catalog within my SRC folder, using MTL, OBJ, and texture files. However, upon switching to the 3D viewer, I encountered an error while att ...

There was an issue attempting to access the 'host' property as it was undefined

I am facing an issue while trying to establish a connection between my application and MongoDB. The error message 'Error: Cannot read properties of undefined (reading 'host')' keeps popping up, and I'm unable to pinpoint the root c ...

Is the button inactive until an action is taken?

In my coding project, I am working with two buttons. I am trying to figure out a way to disable the second button until the first button is clicked. Does anyone have any suggestions on how to achieve this using a combination of JavaScript and CSS? ...

Overusing For Loops for Cloning in JavaScript

REVISED: (I have pinpointed the issue previously discussed in the comments) this is the code I am working with: <script type="text/javascript"> for(var i=0; i<5; i++){ $(".image-wrap").clone().appendTo(".container").attr(&apo ...