Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jasmine angular-mocking http请求_Javascript_Angularjs_Unit Testing_Http_Jasmine - Fatal编程技术网

Javascript Jasmine angular-mocking http请求

Javascript Jasmine angular-mocking http请求,javascript,angularjs,unit-testing,http,jasmine,Javascript,Angularjs,Unit Testing,Http,Jasmine,我刚刚读了很多关于模拟$http的文章,我的代码有点问题。我仍然有错误:没有挂起的刷新请求 我在controllers.js中的方法与此类似(browserDebugMode、webRoot、commentsAction都是全局变量-我不想将其设为全局变量:D) 现在对它进行测试: var browserDebugMode = true; var webRoot = "http://localhost/name"; var commentsAction = '/commentsMobile.ph

我刚刚读了很多关于模拟$http的文章,我的代码有点问题。我仍然有错误:没有挂起的刷新请求

我在controllers.js中的方法与此类似(browserDebugMode、webRoot、commentsAction都是全局变量-我不想将其设为全局变量:D)

现在对它进行测试:

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,仅此而已。我不知道我做错了什么。我在那个控制器中测试了其他东西,一切正常,我查看了getComments()是否与console.log一起触发,它是否被触发。配置它一定有问题。

您的测试代码和单元测试在不同的上下文中执行,因此它们将具有不同的全局对象,因此测试中存在的
浏览器调试模式与实际代码中的模式不同

控制器应注入
$window
(Angular在
窗口
对象周围的包装),然后检查该对象的
浏览器调试模式
属性:

if ($window.browserDebugMode) {
    // actual code
}
beforeEach(inject(function ($window) {
    $window.browserDebugMode = true;
}));
测试还应插入
$window
,然后设置该属性的
browserDebugMode
属性:

if ($window.browserDebugMode) {
    // actual code
}
beforeEach(inject(function ($window) {
    $window.browserDebugMode = true;
}));
现在,控制器和测试都将引用同一个全局对象,
if
条件应为true,并且应执行
$http
调用