茉莉花单元测试工厂



我是Jasmine测试的新手,在这里我想测试工厂中的$资源,所以我有第一个工厂:

angular.module('starter.services', [])
  .factory('API', function($rootScope, $resource) {
    var base = "http://192.168.178.40:8000/api";
    return {
      getGuestListForH: $resource(base + '/guests/:id/:wlist', {
        id: '@id',
        wlist: '@wlist'
      })
    }
  });

and my test:

beforeEach(module('starter.services'));
describe('service: API resource', function() {
  var $scope = null;
  var API = null;
  var $httpBackend = null;
  beforeEach(inject(function($rootScope, _API_, _$httpBackend_) {
    $scope = $rootScope.$new();
    API = _API_;
    $httpBackend = _$httpBackend_;
    $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{
      id: 1,
      name: 'a'
    }, {
      id: 2,
      name: 'b'
    }]);
  }));
  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });
  it('expect all resource in API to br defined', function() {
    $httpBackend.expect('http://192.168.178.40:8000/api/guests');
    var dd = API.getGuestListForH.query();
    expect(dd.length).toEqual(2);
    expect(API.getGuestListForH).toHaveBeenCalled();
  });
});

and I got in the result:

  • 期望0等于2
    • 期待间谍但得到了功能我想测试一下工厂的资源,最好的方法是什么?!

即使没有$rootScope和您所做的所有其他变量声明,您的测试也可以完成。

既然你是在为Service的方法编写测试,而不是用expect代替toHaveBeenCalled,你应该调用它,并期望结果是什么

像这样:

describe('Service: starter.services', function() {
    beforeEach(module('starter.services'));
    describe('service: API resource', function() {
        beforeEach(inject(function(_API_, _$httpBackend_) {
            API = _API_;
            $httpBackend = _$httpBackend_;
            $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{
                id: 1,
                name: 'a'
            }, {
                id: 2,
                name: 'b'
            }]);
        }));
        afterEach(function() {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });
        it('expect all resource in API to br defined', function() {
            var dd = API.getGuestListForH.query();
            $httpBackend.flush();
            expect(dd.length).toEqual(2);
        });
    });
});

最新更新