lundi 27 juillet 2015

Unit testing a service with $resource, $httpbackend vs mocking

When unit testing a service that usings $resource, what is best practice - using $httpBackend or mocking the resource?

I have the following service:

  angular.module('example')
    .factory('MyService', ['$resource',
      function($resource) {

       var service = $resource('/api/example/', {}, {
          create: {
            method: 'POST'
          }
        });

        var create = function(payload) {
          return service.create({}, payload).$promise;
        };

        return {
          create: create
        };
      }
    ]);

Using $httpbackend

    describe('#create', function() {
      it('should send a post request to api/example', function() {
        $httpBackend.expectPOST('/api/example')
          .respond({
            name: 'Something'
          });

        MyService.create({ example: 'payload' }});

        $httpBackend.flush();

        expect(MyService.create).toEqual({example: 'payload'})
      });
    });

Aucun commentaire:

Enregistrer un commentaire