AngularJS单元测试指令查询服务器返回“不满意的请求”

时间:2014-03-10 15:55:52

标签: angularjs unit-testing angularjs-directive httpbackend

我有一个书签应用程序,它接受一个网址并自动提取摘要。当客户端请求服务器添加新书签时,服务器会发回一些初始信息并启动一个提取摘要的过程。

在角度前端,我创建了添加书签和管理书签列表中每个项目的指令。在listitem指令中有一个checkSummary()方法,它将轮询服务器以获取摘要。

我对后一个指令的单元测试有问题。它失败了“不满意的请求”但是当我在各个点登录到控制台时,$http.get()请求似乎触发了,我可以看到$ scope变量已更新,所以我真的不明白为什么它会失败原因。我已经检查了许多不同问题的答案,但是找不到能给出一些见解的任何东西。

代码如下:

bookmarks.js:

angular.module( 'userpages.bookmarks', [
  'ui.router',
  'ui.bootstrap',
  'ui.validate'
])

.config(function config( $stateProvider ) {
  $stateProvider.state( 'userpages.bookmarks', {
    url: '/bookmarks',
    templateUrl: 'userpages/bookmarks/bookmarks.tpl.html',
    controller: 'BookmarksController',
    data: { pageTitle: 'Bookmarks' },
  });
})

.factory('bookmarksApiResource', ['$http', function ($http) {
  var bookmarksUrl = '/api/v1/bookmarks/';
  var api = {
    getList: function() {
      return $http.get( bookmarksUrl )
              .then( function(response) { return response.data; });
    },
    getById: function(id) {
      return $http.get( bookmarksUrl + id + '/' )
              .then( function(response) { return response.data; });
    },
    addBookmark: function(articleUrl) {
      return $http.post( bookmarksUrl, {article_url: articleUrl})
              .then( function(response) { return response.data; });
    },
    checkSummary: function(id) {
      return $http.get( bookmarksUrl + id + '/?fields=summary' )
              .then( function(response) { return response.data; });
    }
  };
  return api;
}])

.controller( 'BookmarksController', ['$scope', '$stateParams', 'bookmarksApiResource',
   function BookmarksController( $scope, $stateParams, bookmarksApiResource) {

    $scope.username = $stateParams.username; 
    $scope.templates = {
      bookmarks: {
        toolbar: 'userpages/bookmarks/bookmarks-toolbar.tpl.html',
        listitem: 'userpages/bookmarks/bookmarks-listitem.tpl.html',
      }
    };
    $scope.addBookmarkFormCollapsed = true;

    $scope.bookmarks = [];
    bookmarksApiResource.getList().then( function(data) {
      $scope.bookmarks = data;
    });
}])

.directive('newBookmark', ['bookmarksApiResource', function(bookmarksApiResource) {
  var newBookmark = {
    restrict: 'E',
    templateUrl: 'userpages/bookmarks/bookmarks-add-form.tpl.html',
    replace: true,
    link: function($scope, $element, $attrs, $controller) {
      $scope.addBookmark = function(articleUrl) {
        var newBookmark = bookmarksApiResource.addBookmark(articleUrl);
        $scope.bookmarks.push(newBookmark);
      };
    }
  };
  return newBookmark;
}])

.directive('bookmarksListitem', ['bookmarksApiResource', '$timeout',
                                 function(bookmarksApiResource, $timeout) {
  var listitem = {
    restrict: 'E',
    templateUrl: 'userpages/bookmarks/bookmarks-listitem.tpl.html',
    replace: true,
    scope: true,
    link: function($scope, $element, $attrs, $controller) {

      var checkSummary = function() {
        if (!$scope.bookmark.summary_extraction_done) {
          bookmarksApiResource.checkSummary($scope.bookmark.id).then(function(data){
            if (data.summary_extraction_done) {
              $scope.bookmark.summary_extraction_done = data.summary_extraction_done;
              $scope.bookmark.summary = data.summary;
            } else {
              $timeout(checkSummary, 1000);
            }
          });
      }

      checkSummary();
    }
  };
  return listitem;
}])
;

,测试如下:

bookmarks.spec.js

describe( 'userpages.bookmarks', function() {

  var $rootScope, $location, $compile, $controller, $httpBackend;
  var $scope, elem;

  beforeEach( module( 'userpages.bookmarks', 'ui.router' ) );

  ... other tests ...

  describe('bookmarks-listitem', function() {
    var testBookmark; 

    beforeEach(module('userpages/bookmarks/bookmarks-listitem.tpl.html'));
    beforeEach(inject(function(_$rootScope_, _$compile_, _$httpBackend_){
      $rootScope = _$rootScope_;
      $compile = _$compile_;
      $httpBackend = _$httpBackend_;

      testBookmark = {
        id: 1,
        title: 'Title of our first article',
        url: 'http://www.example.com/some/article',
        summary_extraction_done: false,
        summary: '',
      };

    }));

    it('when summary_extraction_done = false, checkSummary() should call the server and update the summary with the response', function () {
      $httpBackend.when('GET', '/api/v1/bookmarks/1/?fields=summary').respond(200, {
        summary_extraction_done: true,
        summary: 'This is the summary for article 1.'
      });
      $httpBackend.expect('GET', '/api/v1/bookmarks/1/?field=summary');

      $scope = $rootScope.$new();
      $scope.bookmark = testBookmark;
      elem = $compile('<bookmarks-listitem></bookmarks-listitem>')($scope);
      $scope.$digest();
      $httpBackend.flush();

      expect($scope.bookmark.summary_extraction_done).toBe(true);
      expect($scope.bookmark.summary).toBe('This is the summary for article 1.');
    });

  });
});

测试结果如下:

Firefox 27.0.0 (Mac OS X 10.9) userpages.bookmarks bookmarks-listitem when summary_extraction_done = false, checkSummary() should call the server and update the summary with the respone FAILED
    Error: Unsatisfied requests: GET /api/v1/bookmarks/1/?field=summary in .../frontend/vendor/angular-mocks/angular-mocks.js (line 1486)
    createHttpBackendMock/$httpBackend.verifyNoOutstandingExpectation@.../frontend/vendor/angular-mocks/angular-mocks.js:1486
    createHttpBackendMock/$httpBackend.flush@.../frontend/vendor/angular-mocks/angular-mocks.js:1464
    @.../frontend/src/app/userpages/bookmarks/bookmarks.spec.js:6

任何建议都会有所帮助。

2 个答案:

答案 0 :(得分:9)

如果您想查看httpBackend使用的URL,可以使用以下代码进行调试。

$httpBackend.when("GET", new RegExp('.*')).respond(function(method, url, data) {
   console.log("URL:",url);
});

答案 1 :(得分:5)

错字:

$httpBackend.expect('GET', '/api/v1/bookmarks/1/?field=summary');

您在字段末尾缺少 s