Umair Jameel
Umair Jameel

Reputation: 1673

How to test service function having $q promise with karma in AngularJS

I have a service and inside that service, I have function like so

 settings.updateProfile = function(patient){
        return $q(function(resolve, reject) {
            var user = patient;
                dbService.updateUser(user).then(
                    function (response) {
                        if (response.res) {
                            LoopBackAuth.setUser(LoopBackAuth.accessTokenId, response.res.name, LoopBackAuth.currentUserRole);
                            LoopBackAuth.save();
                            location.reload();
                            patient.name == response.res.name ? resolve(true) : resolve(false);
                        }
                    },
                    function (error) {
                        resolve(false);
                    }
                );

        });
    };

Here dbService.updateUser function contain $promise as well. I want to test this function and check if it resolved true or false. I know for http api call we use $httpBackend service. But It is not working as I am expecting. Right now I am testing it like this.

  it('Should return correct result', function() {
        var result = true;
        var patient = {"name": "newUser"};

        $httpBackend.whenGET(patient).respond(200, $q.when(result));
        expect(settingsFactory.updateProfile).not.toHaveBeenCalled();
        expect(result).toEqual(true);

        settingsFactory.updateProfile(patient)
            .then(function(res) {
               result = res;
            });

        $httpBackend.flush();
        expect(settingsFactory.updateProfile).toHaveBeenCalledWith(patient);
    });

It showing error:

 Error: Unexpected request

Upvotes: 1

Views: 48

Answers (1)

Rocky Sims
Rocky Sims

Reputation: 3618

$httpBackend.whenGET(patient).respond(...);

is failing because patient is an object {"name": "newUser"} and whenGET is expecting a string. For example:

$httpBackend.whenGET('/patient').respond(...);

Upvotes: 1

Related Questions