茉莉花单元测试工厂

时间:2016-10-09 20:34:00

标签: angularjs unit-testing jasmine karma-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'
      })
    }
  });

和我的测试:

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();

  });
});

我得到了结果:

  • 预期0到2
    • 预期的间谍但有功能 这里有什么不对。我想在工厂测试资源最好的方法是什么?!

1 个答案:

答案 0 :(得分:0)

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

由于您正在为服务方法编写测试,而不是expecttoHaveBeenCalled,您应该调用它并期望结果是什么。< / p>

这样的事情:

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);
        });
    });
});

希望这有帮助。