【问题标题】:Jasmine: no pending request to flushJasmine:没有待处理的刷新请求
【发布时间】:2015-11-21 11:15:06
【问题描述】:

我按照“Hands on agular”课程的说明 (https://code.tutsplus.com/courses/hands-on-angular),编写了以下控制器测试:

'use strict';
describe('Controller: EventsController', function () {

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

  var EventsController,
    scope, http, response;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, $httpBackend) {
    http = $httpBackend;
    response = [{ key: '1' }];
    http.whenGET('/api/events').respond(response);
    scope = $rootScope.$new();
    EventsController = $controller('EventsController', {
      $scope: scope
      // place here mocked dependencies
    });
  }));

  afterEach(function(){
      http.verifyNoOutstandingExpectation();
      http.verifyNoOutstandingRequest();
  });

  it('should request to api', function () {
      http.expectGET('/api/events');
      http.flush();
  });
});

当我运行此测试时,我收到“没有待处理的刷新请求”错误...

这是我的事件控制器:

'use strict';

angular.module('ekApp')
.controller('EventsController', function($scope, Event, Category){
    $scope.categories = [{name: 'All'}];

    $scope.serverCategories = Category.query(function(){
        $scope.categories = $scope.categories.concat($scope.serverCategories);
    });

    console.log($scope.categories);

    $scope.events = Event.query();

    console.log($scope.events);

    $scope.filterBy = {
        search: '',
        category: $scope.categories[0],
        startDate: new Date(2015,4,1),
        endDate: new Date(2016,1,14)
    };
});

还有我的事件服务,它返回资源:

'use strict';

angular
    .module('ekApp')
    .factory('Event', function($resource){
        return $resource('/api/events/:id', { id: '@id' });
    });

【问题讨论】:

    标签: angularjs unit-testing karma-jasmine


    【解决方案1】:

    只需向上滚动终端,您就会看到实际的错误:

    Unknown provider: $resourceProvider <- $resource <- Event
    

    您需要使用 angular-resource 作为依赖项并将其作为依赖模块添加到您的应用程序中。

    angular.module('ekApp',['ngResource'])
    

    另外,不要忘记在 karma-conf.js 中添加 angular-resource.js

      'app/bower_components/angular-resource/angular-resource.js',
    

    【讨论】:

    • 您指定的所有内容在测试前都已完成。我在终端看到的是:PhantomJS 1.9.8 (Linux 0.0.0) Controller: EventsController should request to api FAILED Error: No pending request to flush !在 /home/serzh/dev/EventKicker_Frontend/bower_components/angular-mocks/angular-mocks.js:1544 在 /home/serzh/dev/EventKicker_Frontend/test/spec/controllers/events.js:30 PhantomJS 1.9.8 (Linux 0.0.0):执行 3 of 3 (1 FAILED) (0.045 secs / 0.056 secs)
    • 有趣的是,当我在我的机器上执行这些测试时,angular-resource 是唯一缺少的东西。当我包括在内时,错误就消失了。当然,我评论过Category.query()方法调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2015-09-11
    • 2012-12-11
    • 2019-11-28
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多