Skip to content

Instantly share code, notes, and snippets.

@delbetu
Created December 13, 2016 15:12
Show Gist options
  • Save delbetu/2c9346465d71c6ddb24e57329cf7d9b6 to your computer and use it in GitHub Desktop.
Save delbetu/2c9346465d71c6ddb24e57329cf7d9b6 to your computer and use it in GitHub Desktop.
Angular Factory Test Example

##Example Service

  angular.module('sportAdmin')
    .factory('Tournament', function($resource, $q) {

      var baseUrl = '/api/tournaments/:tournamentId'

      var service = $resource(baseUrl, {tournamentId: '@id'})

      function all() {
        return service.query()
      }

      function find(id) {
        return service.get({tournamentId: id})
      }

      function create(tournament, success, error) {
        return service.create(tournament, success, error)
      }

      function destroy(id, success, error) {
        return service.delete({tournamentId: id}, success, error)
      }

      return {
        all: all,
        find: find,
        create: create,
        destroy: destroy
      }
  })

##Example Service Test

    describe('Tournament', function () {

      beforeEach(angular.mock.module('sportAdmin'))

      beforeEach(function () {

        angular.mock.inject(function ($injector) {
          $httpBackend = $injector.get('$httpBackend')
           tournamentService = $injector.get('Tournament')
        })

        $httpBackend.expect('GET', '/api/user').respond({})

        cb = jasmine.createSpyObj('callback', ['success', 'error'])
      })

      describe('.all()', function () {
        it('should retrieve all the tournaments', function () {

          $httpBackend.expectGET('/api/tournaments').respond(200, tournamentData)

          var result = tournamentService.all( function() {
            expect(result).toBe(tournamentData)
          })

          $httpBackend.flush()
        })
      })

      ...

      describe('.create()', function () {
        it('create the new tournament', function () {

          var tournament = {"name":"Test Tournament","sport_id":4,"org_id":1}

          $httpBackend.expectPOST('/api/tournaments', tournament).respond(201, tournament)

          tournamentService.create(tournament, cb.success, cb.error)

          $httpBackend.flush()

          expect(cb.success).toHaveBeenCalled()
        })
      })

      ...

    })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment