4

所以我是 angularjs 及其模拟库的新手。我正在尝试测试是否发出了特定的 GET 请求,但是对于第二个断言,我总是会收到此错误,并且无法弄清楚原因:

Error: Unsatisfied requests: GET /1.json

我在下面的代码中有什么搞砸了吗?

应用程序.js

var App = angular.module('App', []).config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
  }).when('/Items', {
    templateUrl: 'views/items.html',
    controller: 'Ctrl'
  }).otherwise({
    redirectTo: '/'
  });
}]);

Ctrl.js

function Ctrl($scope, $http, $filter) {
  $scope.items = [];

  $http.get('/1.json').success(function(data) {$scope.items = data.items;});
}

Ctrl.$inject = ["$scope","$http", "$filter"];

规范/Ctrl.js

describe('Controller: Ctrl', function() {
  var $httpBackend;
  // load the controller's module
  beforeEach(module('App'));
  beforeEach(inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');

    // backend definition common for all tests
    $httpBackend.whenGET('/1.json').respond('Response!');
  }));

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

  var Ctrl, scope;

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

    scope = $rootScope.$new();
    Ctrl = $controller('Ctrl', {
      $scope: scope
    });
  }));

  it('should initialize with 0 items', function() {
    expect(scope.items.length).toBe(0);
    $httpBackend.flush();
  });

  it('should make store request', function(){
    var controller = scope.$new(Ctrl);
    $httpBackend.expectGET('/1.json');
    $httpBackend.flush();
  });
});

编辑:添加应用程序和控制器代码。

4

1 回答 1

5

我终于让我的单元测试工作了!主要是因为我重组了我的应用程序以使其更有意义和更模块化。

我将尝试提供信息以帮助遇到此问题的下一个人:

首先是我改用 $resource 而不是 $http。

我没有注入 $injector,而是注入了 $httpBackend,如下所示:

beforeEach(inject(function(_$httpBackend_, $rootScope, $route,  $controller){

  $httpBackend = _$httpBackend_;
  $httpBackend.expectGET('/path/to/api').respond([{id:1}]);

我没有将“Ctrl”作为字符串引用,而是传入了实际的类

Ctrl = $controller('Ctrl', { $scope: scope });

变成了

var ProductsCtrl = ['$scope', function($scope){ ... }];

Ctrl = $controller(ProductsCtrl, {
  $scope: scope
});`

如果您使用 $resources,请确保您引用了 angular-resources.js 文件

我真的很喜欢 Angularjs;我认为只需要一些时间来思考如何测试。祝你好运!

于 2013-02-25T07:40:13.017 回答