测试Angular-Resource:期望一个对象,得到一个资源

时间:2016-06-09 21:26:34

标签: angularjs jasmine angular-resource httpbackend

当尝试使用$resource测试一些简单的角度代码时,我最终得到一个Resource对象,其中包含$promise键,因此表单失败:{{1} }

我希望在Failure/Error: Expected Resource(...) to equal Object(...)中找回我传递给respond方法的对象。我使用httpBackend.expectGET('/books/5.json').respond(my_book)错了或者我的测试中出了什么问题?

代码

$resource

测试

var bookApp = angular.module('bookApp',
  [
  'ngResource',
  ]
);

function BookController(scope, $resource) {
  var ctrl = this;
  var Book = $resource('/books/:selected.json', {selected:'@id'});

  ctrl.fetch_book = function(id){
    console.log('Selecting options ' + id);
    Book.get({selected:id}, function(data){
      console.log('Received: ' + JSON.stringify(data));
      ctrl.current_book = data;
    });
  };
}

BookController.$inject = ['$scope', '$resource'];

bookApp.component('book', {
  controller: BookController
});

结果

describe('component: tree', function() {
  var component_controller, $componentController, httpBackend, my_book;

  beforeEach(module('bookApp'));

  beforeEach(inject(function($httpBackend, _$componentController_) {
    httpBackend = $httpBackend;
    $componentController = _$componentController_;
  }));

  describe('$ctrl.fetch_book(book_id)', function(){

    beforeEach(function() {
      component_controller = $componentController('book');
      my_book = {title: 'Sanctuary', id: '5'};
    });

    it('fetches the book with id=book_id', function(){
      httpBackend.expectGET('/books/5.json').respond(my_book);
      component_controller.fetch_book(5);
      httpBackend.flush();
      console.log('Options: ' + JSON.stringify(component_controller.current_book));
      console.log('constructor: ' + JSON.stringify(component_controller.current_book.constructor.name));
      expect(component_controller.current_book).toEqual(my_book);
    });
  });
});

3 个答案:

答案 0 :(得分:1)

在测试仪中试试这个:

expect(component_controller.current_book).toEqual(angular.toJSON(my_book));

它会删除对象的属性并且您将匹配。

你也可以试试angular.equals,但我还没有测试过。

答案 1 :(得分:1)

尝试将以下内容添加到您的spec文件中,看看它是否有效。我在PhoneCat示例中看到它,它对我有用。

 beforeEach(function() {
    jasmine.addCustomEqualityTester(angular.equals);
  });

答案 2 :(得分:0)

您可以尝试这样做:

expect(component_controller.current_book.toJSON()).toEqual(my_book);

我遇到了同样的错误

  

预期对象是一种对象,但是资源(

这就是我之前所拥有的:

expect(self.project).toEqual(mockProject);

在我添加.toJSON()后,一切都很好:

expect(self.project.toJSON()).toEqual(mockProject);

希望这有帮助!