简体   繁体   中英

How to unit test an angularjs promise

I would you unit test a promise like this:

 function getSongs() {
    var d = $q.defer();
    var URL = 'http://localhost:3002/songs';

    $http({
      method: 'GET',
      url: URL
    })
    .success(function(data) {
      d.resolve(data);
    })
    .error(function(data) {
      d.reject(data);
    });

    return d.promise;
  }

This returns and arrays of objects. Then I used this in the controller by simply calling the getSongs function:

var vm = this;

vm.songList = [];

vm.init = function () {
  PlayerScreenService.getSongs()
    .then(getSongsSuccess);
};

vm.init();

Thank you very much.

Take a look at $httpBackend . Your test could look something like this:

describe('PlayerScreenService', function () {

    it('should send HTTP request', inject(function (PlayerScreenService, $httpBackend) {
        $httpBackend.whenGET('http://localhost:3002/songs').respond(200, {...});

        var getSongsSuccess = jasmine.createSpy('getSongsSuccess');
        var getSongsError = jasmine.createSpy('getSongsError');
        PlayerScreenService.getSongs()
            .then(getSongsSuccess, getSongsError);

        $httpBackend.flush();
        expect(getSongsSuccess).toHaveBeenCalledWith({...});
        expect(getSongsError).not.toHaveBeenCalled();
    }));

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM