Pramodh
Pramodh

Reputation: 186

httpBackend.expectPUT not working in angularjs factory unit test

Below is the sample service that I'm trying to unit test:

    angular.module('sampleModule')
        .factory('sampleService', sampleService);

    sampleService.$inject = ['$http'];

    function sampleService($http) {
        var endpoint = "http://localhost:8088/api/customers/"
        return {
            getData: function(id){
                return $http({
                    method: 'GET',
                    url: endpoint + id
                });
            },
            updateData: function(id, requestBodyObject){
                return $http({
                    method: 'PUT',
                    url: endpoint + id,
                    data: requestBodyObject

                });
            }
        };
    }

Below is the sample spec that I have to test the above service. However its throwing error

    describe('Sample Service', function(){

        var service, httpBackend;

        beforeEach(function(){
            angular.mock.module('sampleModule');

            angular.mock.inject(function(_sampleService_, $httpBackend){
                service = _sampleService_;
                httpBackend = $httpBackend;
            });
        });


        it('updateAdvisorAttributesData should return response on valid acctNumber', function(){
            var response = {};
            var errResponse = {};
            var id = 1234;
            var requestBody = {
              '1': 'one'
            };
            var endpoint = "http://localhost:8088/api/customers/"

            httpBackend.expectPUT(endpoint + id, requestBody).respond(200, {'key': 'value'});

            service.updateData(id).then(function(result){
                response = result;
            },function(error){
                errResponse = error;
            });

            httpBackend.flush();
            expect(response.status).toBe(200);
            expect(response.data).toEqual({'key': 'value'});

        });
    });

Error on executing the spec:

    Error: Expected PUT http://localhost:8088/biga/advisors/1234 with different data
    EXPECTED: {"1":"one"}
    GOT:      undefined

The same approach worked for httpBackend.expectGET(). However its failing for PUT. Why is failing? How do I fix it?

Upvotes: 0

Views: 868

Answers (1)

Austin
Austin

Reputation: 1291

You're not passing a body when you're doing the test.

Change:

service.updateData(id).then(function(result){

to:

service.updateData(id, requestBody).then(function(result){

Upvotes: 1

Related Questions