Testing Angular $resource with external service

前端 未结 2 1372
离开以前
离开以前 2021-01-06 12:12

I\'m trying to make some basic tests on REST requests I\'m doing using Angular $resource. The service code works just fine.

\'use strict\';

angular.module(         


        
相关标签:
2条回答
  • 2021-01-06 12:48

    You were very close, the only thing missing was a call to the $httpBackend.flush();. The working test looks like follows:

    it('returns a JSON', inject(function(Device) {
      var device = Device.get({ id: '50c61ff1d033a9b610000001' });
      $httpBackend.flush();
      expect(device.name).toEqual('Light');
    }));
    

    and a live test in plunker: http://plnkr.co/edit/Pp0LbLHs0Qxlgqkl948l?p=preview

    You might also want to check docs for the $httpBackend mock.

    0 讨论(0)
  • 2021-01-06 12:51

    In later versions of angular, I'm using 1.2.0rc1 you also need to call this within a $apply or call $digest on a scope. The resource call isn't made unless you do something like this:

    var o, back, scope;
    
    beforeEach(inject(function( $httpBackend, TestAPI,$rootScope) {
        o = TestAPI;
        back = $httpBackend;
        scope = $rootScope.$new();
    
    }));
    
    it('should call the test api service', function() {
        back.whenGET('/api/test').respond({});
        back.expectGET('/api/test');
        scope.$apply( o.test());
        back.flush();
    });
    
    0 讨论(0)
提交回复
热议问题