3

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

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

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

代码如下:

书签.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;
}])
;

测试如下:

书签.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

任何的意见都将会有帮助。

4

2 回答 2

9

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

$httpBackend.when("GET", new RegExp('.*')).respond(function(method, url, data) {
   console.log("URL:",url);
});
于 2015-09-30T09:40:25.527 回答
5

在这里打错字:

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

您在字段末尾缺少一个s

于 2014-03-10T17:37:08.727 回答