1

嗨,我目前正在使用 karma 和 jasmine 设置一些单元测试。而且我在尝试完全测试 ng 资源时遇到了困难。当我做一个 scope.clients.query() 是执行一个请求。但是当我尝试在单元测试中这样做时,这将失败。

有人有类似的问题吗?有人知道如何解决这个问题吗?

例如

var mockResponse = [[{
      "name": "foo",
    },{
      "name": "foo",
    }
  ];
describe("adserver module", function() {

  //define module
  beforeEach(module('someModule'));

  describe("some controller", function() {

    var scope, controller, $httpBackend;

    var CTRL = 'someCtrl';

    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
      $httpBackend = _$httpBackend_;
      scope = $rootScope.$new();
      controller = $controller;
    }));

    afterEach(function() {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    beforeEach(function() {
      //define requests and responses
      $httpBackend.expectGET('/api/clients').respond(mockResponse);

      //aplly controller
      controller(CTRL, {
        $scope: scope
      });

      // flush all request
      $httpBackend.flush();
    });

    //SPECS
      it('should contain clients', function() {
      expect(typeof scope.clients).toBe('object');
      expect(scope.clients.length).toBe(2);
    });

    it('scope should re-request', function() {
      scope.clients.query();  /// will not work methode undefined
      expect(scope.clients.length).toBe(2);
    });
  });
});
4

1 回答 1

0

您没有正确使用 $httpBackend。

一、mock响应的定义:

$httpBackend.whenGET('/api/clients').respond(mockResponse);

然后,后来,期望:

$httpBackend.expectGET('/api/clients');
$httpBackend.flush();
于 2014-08-21T13:54:37.297 回答