javascript - Jasmine angular - 模拟http请求

标签 javascript angularjs unit-testing http jasmine

我刚刚阅读了很多关于模拟 $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/

相关文章:

javascript - 如果导入 events-polyfill,React Datepicker 将无法正常工作

javascript - ng-click 第二次无法使用 ng-hide 交互

javascript - 添加新行后,React.js 从 Mongo DB 更新表

javascript - Angular Directive(指令)内的 jquery 日期选择器

Angularjs 用户界面 :sortable in ng:repeat not behaving as expected

java - 使用 Tomcat 5.5,如何以编程方式定位特定的 servlet 实例或添加新的映射?

java - JUnit 5 中的 @TestInstance 注释有什么用?

Angular 单元测试 : how to use marble testing (rxjs/testing) to test this state management service

javascript - SVG/CSS 问题,嵌入或引用文件

javascript - 使用API​​停止YouTube视频时如何显示缩略图?