【发布时间】:2013-01-23 20:01:08
【问题描述】:
所以我是 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();
});
});
编辑:添加应用和控制器代码。
【问题讨论】:
-
您的代码表明您期望“获取”请求,但我看不到它是在哪里发出的,这就是您收到错误的原因。您希望该请求在哪里发生?
-
抱歉,我忘了包含应用程序和控制器代码。我已经这样做了,我的错误是否可能是由于 routeProvider 而发生的?我需要告诉我的测试以某种方式执行路由吗?
标签: javascript unit-testing angularjs