所以我是 angularjs 及其模拟库的新手。我正在尝试测试是否发出了特定的 GET 请求,但我总是在第二个断言中收到此错误并且无法弄清楚原因:
Error: Unsatisfied requests: GET /1.json
我下面的代码有什么问题吗?
App.js
var App = angular.module('App', []).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
}).when('/Items', {
templateUrl: 'views/items.html',
controller: 'Ctrl'
}).otherwise({
redirectTo: '/'
});
}]);
Ctrl.js
function Ctrl($scope, $http, $filter) {
$scope.items = [];
$http.get('/1.json').success(function(data) {$scope.items = data.items;});
}
Ctrl.$inject = ["$scope","$http", "$filter"];
规范/Ctrl.js
describe('Controller: Ctrl', function() {
var $httpBackend;
// load the controller's module
beforeEach(module('App'));
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
$httpBackend.whenGET('/1.json').respond('Response!');
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
var Ctrl, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
Ctrl = $controller('Ctrl', {
$scope: scope
});
}));
it('should initialize with 0 items', function() {
expect(scope.items.length).toBe(0);
$httpBackend.flush();
});
it('should make store request', function(){
var controller = scope.$new(Ctrl);
$httpBackend.expectGET('/1.json');
$httpBackend.flush();
});
});
编辑:添加了应用程序和 Controller 代码。
最佳答案
我终于让我的单元测试工作了!主要是因为我重组了我的应用程序以使其更有意义和更模块化。
我将尝试提供信息以帮助遇到此问题的下一个人:
首先是我改用 $resource 而不是 $http。
我没有注入(inject) $injector,而是像这样注入(inject) $httpBackend:
beforeEach(inject(function(_$httpBackend_, $rootScope, $route, $controller){
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('/path/to/api').respond([{id:1}]);
我没有将“Ctrl”作为字符串引用,而是传入了实际的类
Ctrl = $controller('Ctrl', {
$范围:范围
});
成为
var ProductsCtrl = ['$scope', function($scope){ ... }];
Ctrl = $controller(ProductsCtrl, {
$scope: scope
});`
如果您使用 $resources,请确保您引用的是 angular-resources.js 文件
我真的很喜欢 Angularjs;我认为您只需要花一些时间来思考如何测试。祝你好运!
关于javascript - AngularJS 问题模拟 httpGET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14766051/