How to test XMLHttpRequest with Jasmine

后端 未结 6 1157
心在旅途
心在旅途 2021-02-19 16:43

How can I test the onreadystatechange on XMLHttpRequest or pure Javascript AJAX without jQuery? I\'m doing this because I\'m developing Firefox extension. I guess I have to use

6条回答
  •  遥遥无期
    2021-02-19 17:01

    Provided by jasmine-ajax. To mock for a single spec use withMock:

      it("allows use in a single spec", function() {
        var doneFn = jasmine.createSpy('success');
        jasmine.Ajax.withMock(function() {
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function(args) {
            if (this.readyState == this.DONE) {
              doneFn(this.responseText);
            }
          };
    
          xhr.open("GET", "/some/cool/url");
          xhr.send();
    
          expect(doneFn).not.toHaveBeenCalled();
    
          jasmine.Ajax.requests.mostRecent().respondWith({
            "status": 200,
            "responseText": 'in spec response'
          });
    
          expect(doneFn).toHaveBeenCalledWith('in spec response');
        });
      });
    

    The response is only sent when you use respondWith. Just download the file, and add as a src to your SpecRunner.html. Example usage at https://github.com/serv-inc/JSGuardian (see the test folder).

提交回复
热议问题