单元测试:在控制器内部指令中调用http

时间:2014-08-01 06:47:44

标签: angularjs-directive karma-jasmine httpbackend

describe("File Upload directive", function() {
      var elm, scope,httpBackend , controller , isolateScope;

     beforeEach(angular.mock.module("fileApp"));


     beforeEach(angular.mock.inject(function($rootScope, $compile , $httpBackend) {
          elm = angular.element("<div file-upload base-upload-url='files/' ></div>");
          httpBackend = $httpBackend;
          scope = $rootScope;
          httpBackend.whenGET("fileUploadTemplate.html").respond(true);
          $compile(elm)(scope);
          controller = elm.controller;

          scope.$digest();
    }));

    it("should upload selected file",function(){
      httpBackend.flush();
      isolateScope = elm.isolateScope();
      expect(isolateScope).toBeDefined();

      isolateScope.selectedFiles=[{"webkitRelativePath":"","lastModifiedDate":"2014-05-26T11:15:55.000Z","name":"a.csv","type":"text/csv","size":131}];
      var index = 0;
      httpBackend.expectPOST("files/").respond({"fileId":67603});

      expect(isolateScope.uploadResult.length).toBe(1);
      //httpBackend.flush();
     });
    });

现在,我有情况:

  1. 如果我在httpBackend.flush()区块的开头发表评论it,则isolateScope为undefined
  2. 如果我在httpBackend.flush()阻止结束时发表评论itisolateScope.uploadResult.length = 0建议httpPOST没有按预期正确执行(httpBackend.flush是在http呼叫之后从未打过电话。)
  3. 3.如果我同时保留httpBackend.flush()(不应该这样做),我会收到预期的错误:Error: No pending request to flush !

    有人可以指导我吗?我是业力的新手。

    提前致谢。

1 个答案:

答案 0 :(得分:0)

尝试在describe block中添加这些行。

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

或者您可能没有调用实例化post调用的指令中的函数,否则它应该可以工作。