角度单位测试和httpBackend.expectGET

时间:2015-05-20 02:28:39

标签: angularjs jasmine karma-jasmine

整个测试的新东西。我今天早些时候运行了这个,但是当我没有包含以下行时,我遇到的一个问题是GET错误:

httpBackend.expectGET('view/contents/home.html').respond(200, ''); 

这有什么用?我为什么需要这个?我正在测试的控制器没有引用该文件。有人可以解释为什么它试图抓住那个模板吗?

var controllers = angular.module('app.controllers', ['app.projects']);

controllers.controller('MainCtrl', function($scope, foo) { 
  $scope.currentStatus = null;


$scope.init = function (){
  foo.fn().then(function(status){
    $scope.currentStatus = status;
      });
  }

});

describe('Controllers:: Master.js', function () {

// load the controller's module
beforeEach(module('app'));

 var scope;
 var foo;
 var stateParams;
 var q;
 var deferred; 
 var rootScope;
 var httpBackend;

// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $q, _$httpBackend_) {

  foo = {
    fn: function() {
              deferred = $q.defer();
              deferred.resolve('bar');
              return deferred.promise;

            }
          };

  scope = $rootScope.$new();
  stateParams = {};
  q = $q;
  rootScope = $rootScope;
  httpBackend = _$httpBackend_;
  httpBackend.expectGET('view/contents/home.html').respond(200, ''); 
  $controller('MainCtrl', {
    $scope: scope,
    $stateParams:stateParams,
    foo: foo,
  });

}));

it('Should call foo fn', function() {
  spyOn(foo, 'fn').and.callThrough();
  scope.init();
  //deferred.resolve('foo');
  scope.$apply();
  expect(foo.fn).toHaveBeenCalled();

  expect(scope.currentStatus).toBe('bar');

});

});

1 个答案:

答案 0 :(得分:0)

更多的挖掘。显然,在我的测试中使用ui-router并调用$ apply(调用$ digest())会导致错误。在我的Describe块中添加它对我有用。

beforeEach(module(function($urlRouterProvider) {
  $urlRouterProvider.deferIntercept();
}));  

更多信息: https://github.com/angular-ui/ui-router/issues/212

相关问题