当尝试使用$resource测试一些简单的角代码时,我得到了一个Resource对象,该对象包含一个$promise键,因此表单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);
});
});
});结果
$ bundle exec teaspoon -f documentation
component: tree
$ctrl.fetch_book(book_id)
fetches the book with id=book_id (FAILED - 1)
# Selecting options 5
# Received: {"title":"Sanctuary","id":"5"}
# Options: {"title":"Sanctuary","id":"5"}
# constructor: "Resource"
Failures:
1) component: tree $ctrl.fetch_book(book_id) fetches the book with id=book_id
Failure/Error: Expected Resource({ title: 'Sanctuary', id: '5',
$promise: Promise({ $$state: Object({ status: 1, value:
<circular reference: Object> }) }), $resolved: true }) to equal
Object({ title: 'Sanctuary', id: '5' }).
Finished in 0.02600 seconds
1 example, 1 failure发布于 2016-06-09 23:06:20
在您的测试器中试试这个:
expect(component_controller.current_book).toEqual(angular.toJSON(my_book));它将剥去对象的属性,您将得到一个匹配。
您也可以尝试angular.equals,但我还没有对其进行测试。
发布于 2017-11-26 08:30:20
尝试将以下内容添加到您的规范文件中,并查看它是否有效。我在PhoneCat的例子中看到了它,它对我起了作用。
beforeEach(function() {
jasmine.addCustomEqualityTester(angular.equals);
});发布于 2018-01-04 21:56:40
你可以尝试这样做:
expect(component_controller.current_book.toJSON()).toEqual(my_book);我也遇到了同样的问题,我的错误是
预期对象是一种对象,但它是Resource(
这是我以前的经历:
expect(self.project).toEqual(mockProject);在我添加.toJSON()之后,一切都很好:
expect(self.project.toJSON()).toEqual(mockProject);希望这能有所帮助!
https://stackoverflow.com/questions/37736472
复制相似问题