javascript - 如何使用 Jasmine 测试 XMLHttpRequest

标签 javascript ajax jasmine

如何在没有 jQuery 的情况下测试 XMLHttpRequest 或纯 Javascript AJAX 上的 onreadystatechange?我这样做是因为我正在开发 Firefox 扩展。我想我必须使用 spy ,但不知道如何使用,因为我的 ajax 不会返回任何东西。


    submit : function() {
        var url = window.arguments[0];
        var request = new XMLHttpRequest();
        request.open("POST", 'http://'+this.host+'/doSomething', true);
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        request.send("param="+param+"&emotions="+this.getParams());
        request.onreadystatechange = function() {
            if(this.readyState == 4) {
                // alert(this.responseText);
            }
        };

    }

最佳答案

那这个呢?

beforeEach(function() {
  // spyOn(XMLHttpRequest.prototype, 'open').andCallThrough(); // Jasmine 1.x
  spyOn(XMLHttpRequest.prototype, 'open').and.callThrough(); // Jasmine 2.x
  spyOn(XMLHttpRequest.prototype, 'send');
});

...

it("should call proper YQL! API", function() {
  podcast.load_feed('http://www.faif.us/feeds/cast-ogg/');

  expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();
});

无需使用任何外部库的纯 Jasmine。

关于javascript - 如何使用 Jasmine 测试 XMLHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8901445/

相关文章:

javascript - SMIL 动画在动态加载的外部 SVG 上失败

asp.net - 在 ASP.NET 中总计 GridView

angularjs - 使用 jasmine 测试 angular.factory 时出现未知的提供程序错误

javascript - 我应该使用 <script> 标签将数据从 PHP 传递到 JavaScript 吗?

javascript - jQuery 字符串使用 split() 方法在空格后拆分字符串

jquery - "Uncaught RangeError: Maximum call stack size exceeded"调用 $.ajax jquery 函数时

php - 就地编辑更新脚本安全性

angular - 如何在 Angular Testing 中检索 ngClass 的值?

javascript - 测试来自 Backbone.View 的触发点击,它会打开一个新的 Backbone.View

javascript - 在 Ajax 中使用 noscript 标签