如何使用Jasmine测试XMLHttpRequest

toy*_*toy 12 javascript ajax jasmine

如何在没有jQuery的情况下测试XMLHttpRequest或纯Javascript AJAX上的onreadystatechange?我这样做是因为我正在开发Firefox扩展.我想我必须使用间谍,但无法弄清楚因为我的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);
            }
        };

    }

mce*_*epl 36

那个呢?

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();
});
Run Code Online (Sandbox Code Playgroud)

纯茉莉花无需使用任何外部库.

  • 这对我有用。但是如何模拟 xhr 响应处理程序,如 onError、onLoad 等? (2认同)

And*_*rle 6

正如在SinonJS的评论中提到的,您可以轻松地模拟XHR对象/创建虚假服务器.


Alv*_*vis 5

你可以用这样的方式测试一下

it("should make XHR request", function() {

   // arrange

    var xhr = {
        open: jasmine.createSpy('open')
    };

    XMLHttpRequest = jasmine.createSpy('XMLHttpRequest');
    XMLHttpRequest.and.callFake(function () {
        return xhr;
    });

    // act

    submit();

    // assert

    expect(xhr.open).toHaveBeenCalled(); 
});
Run Code Online (Sandbox Code Playgroud)