调用$ timeout.flush()会导致错误:意外请求:** URL **不再需要请求

时间:2015-06-26 15:52:40

标签: javascript angularjs jasmine karma-runner angular-promise

我正在测试我的控制器,他做了两件主要的事情:

  • 执行JSONP请求
  • 执行返回承诺的服务功能

为了开始,我只测试我的服务功能getTodaySpecials,但问题是:

我收到此错误:Error: Unexpected request: **URL** No more request expected当我在$timeout.flush()区块中致电it时...

我对Karma / Jasmine很新,所以我不知道这是不是正确的方式?

控制器:

angular.module('restaurant').controller('HomeCtrl', ['$scope', '$http', 'Menu', 'CONFIG', function ($scope, $http, Menu, CONFIG) {

    $scope.todaySpecials = [];
    $scope.pictures = [];

    var defaultsPictures = [
      {src: 'app/assets/images/pictures/4.jpg'},
      {src: 'app/assets/images/pictures/1.jpg'},
      {src: 'app/assets/images/pictures/6.jpg'}
    ];

    $http.jsonp(CONFIG.backendUrls.pictures + '?callback=JSON_CALLBACK')
      .success(function (pictures) {

        if (!pictures || pictures.length <= 0) {
          $scope.pictures = defaultsPictures;
          return;
        }

        $scope.pictures = pictures;

      })
      .error(function () {

        $scope.pictures = defaultsPictures;

      });

    Menu.getTodaySpecials().then(function (todaySpecials) {
      $scope.todaySpecials = todaySpecials;
    });

  }]);

测试

describe('HomeCtrl', function () {

  var $scope, ctrl;
  var MenuMock;
  var pictures = [{src: 'something'}];

  beforeEach(function() {

    module('restaurant');

    MenuMock = jasmine.createSpyObj('Menu', ['getTodaySpecials']);

    inject(function($rootScope, $controller, _$timeout_, $q) {

      $scope = $rootScope.$new();

      MenuMock.getTodaySpecials.and.returnValue($q.when(pictures));

      $timeout = _$timeout_;

      ctrl = $controller('HomeCtrl', {
        $scope: $scope,
        Menu: MenuMock
      });

    });

  });

  it('should update todaySpecials asynchronously', function (){

    expect(MenuMock.getTodaySpecials).toHaveBeenCalled();  

    $timeout.flush();

    expect($scope.todaySpecials).toEqual(pictures);

  });

});

0 个答案:

没有答案