我在加载 $resource 对象时遇到问题。
我在父 Controller 中有一些东西
$scope.data = Product.$query();
然后在子 Controller 中,我有
$scope.data.$promise.then(function(product){
console.log(data);
})
我的工厂
angular.module('testApp').factory('Product', ['$resource', function ($resource) {
return $resource('/api/product');
}]);
我将 Product.$query()
放在父 Controller 中的原因是因为我希望它在不同的子 Controller 中共享和使用。
我的测试文件如下
describe('Product test ', function () {
var $httpBackend, childCtrl, scope;
beforeEach(module('testApp', function($provide) {
$provide.value('$log', console);
}));
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
scope = _$rootScope_.$new();
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
childCtrl = _$controller_('childCtrl', {
$scope: scope
});
}));
describe('some test', function() {
it('some test here', function(){
//codes...
})
})
});
当我运行测试时,我得到了
TypeError: 'undefined' is not an object (evaluating '$scope.data.$promise')
我不确定这里发生了什么。有人可以帮我吗?非常感谢
最佳答案
因为我要在 jasmine 中测试 $resource
对象,你需要创建你的 $httpBackend
模拟响应,当你查询 时它会返回$resource
你不应该直接使用`$resource。
describe('Product test ', function () {
var $httpBackend, childCtrl, scope, Product;
beforeEach(module('testApp', function($provide) {
$provide.value('$log', console);
}));
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, Product) {
scope = _$rootScope_.$new();
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
Product = Product;
childCtrl = _$controller_('childCtrl', {
$scope: scope,
Product: Product
});
}));
describe('some test', function() {
it('some test here', function(){
$httpBackend.expect('GET', '/api/product').respond([{ id: 1, name: 'a' }, { id: 2, name: 'b' }]);
childCtrl.data = Product.query();
expect(childCtrl.projects).toEqualData([]);
$httpBackend.flush(); //flushing $httpBackend
expect(childCtrl.data).toEqualData([{ id: 1, name: 'a' }, { id: 2, name: 'b' }]);
})
})
});
更多详情可以引用this link
关于javascript - 我的应用程序中的单元测试问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086963/