我刚刚阅读了很多关于模拟 $http 的文章,发现我的代码有问题。我仍然有错误:No pending request to flush !
我在 controllers.js 中的方法看起来与此类似(browserDebugMode、webRoot、commentsAction 是全局变量 - 将其设为全局变量不是我的主意 :D)
$scope.getComments = function(){
if (browserDebugMode) {
$http({
method : "GET",
url : webRoot+commentsAction,
params : {action: "list"},
})
.success(function(data, status) {
//...
})
.error(function(data, status) {
//...
});
}
}
现在测试它:
var browserDebugMode = true;
var webRoot = "http://localhost/name";
var commentsAction = '/commentsMobile.php';
describe('myApp', function() {
var scope,
httpBackend,
http,
controller;
beforeEach(angular.mock.module('myApp'));
describe('NewsDetailCtrl', function() {
beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
http = $http;
httpBackend.when("GET", webRoot+commentsAction).respond([{}]);
controller = $controller('NewsDetailCtrl', {
'$scope': scope, 'GlobalService': globalService, $http: $http
});
}));
it('checks if AJAX is done', function () {
httpBackend.expectGET(webRoot+commentsAction).respond([{}]);
scope.getComments()
httpBackend.flush();
});
});
});
请不要要求 PHP 脚本 :) 我被迫这样做。
我只是想检查我是否可以测试 $http,仅此而已。我不知道我做错了什么。我在该 Controller 中测试了其他东西并且没问题,我查看了 getComments() 是否被 console.log 触发并且它被触发了。配置它一定有问题。
最佳答案
您的被测代码和单元测试在不同的上下文中执行,因此它们将具有不同的全局对象,因此您的测试中存在的 browserDebugMode
与实际代码中的不同。
Controller 应该注入(inject) $window
(Angular 对 window
对象的包装),然后检查它的 browserDebugMode
属性:
if ($window.browserDebugMode) {
// actual code
}
测试还应该注入(inject) $window
然后设置 browserDebugMode
属性:
beforeEach(inject(function ($window) {
$window.browserDebugMode = true;
}));
现在 Controller 和测试都将引用同一个全局对象,if
条件应该评估为真,并且 $http
调用应该执行。
关于javascript - Jasmine angular - 模拟http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27536320/