How to create stub for ajax function using Jasmine BDD

与世无争的帅哥 提交于 2019-12-10 16:51:34

问题


I'm struggling to find any examples on how to fake an ajax call using Jasmine BDD?

I have a custom ajax function that works like so...

ajax({
    url: 'JSON.php',
    dataType: 'json',           
    onSuccess: function(resp) {
        console.log(resp);
    }
});

...and I've no idea how to create a stub to fake calling the actual ajax function.

I want to avoid calling the ajax function as it could slow down my test suite if a real ajax call to the server takes some time to respond and I've loads of specs in my test suite.

I've heard that you can use spyOn(namespace, 'ajax') but that is annoying straight away as it requires me to wrap my ajax function in an object just to use the spyOn function (but regardless I wasn't able to follow along as I couldn't find any specific examples to fake an ajax call).

I've also heard that you can use createSpy() but again the documentation isn't very helpful (neither is the corresponding wiki on GitHub).

Any help explaining how to use spies to create a fake ajax call would be greatly appreciated!


回答1:


You can use SinonJS mocking framework, which has a build in fake server. You can easily use it with jasmine:

beforeEach(function() {
        server = sinon.fakeServer.create();
        server.respondWith([200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"])
});

Btw. if your ajax function is in the global namespace why not call spyOn(window, 'ajax')




回答2:


Regarding a single function, you may use 'createSpy':

/*var */ajax = createSpy('foo');

var is absent because you want to redefine it, but it is then required that the block where you define this spy is bound to the same scope where real ajax was defined. Or, if you confused with that, use spyOn(window, foo), because you are anyway testing it in the browser.

See this answer for details.

Regarding the ajax call, see Asynchronous Support section in new docs, or better use Clock:

window.ajax = function() {};

var response;

var ajaxSpy = spyOn(window, 'ajax').andCallFake(function(url, callback) {
   setTimeout(function() { callback({ 'foo': 'bar' }); }, 1000);
});

jasmine.Clock.useMock();

function callback(resp) { response = resp;  }

ajax('fake.url', callback);

jasmine.Clock.tick(1500);

expect(ajaxSpy).toHaveBeenCalled();
expect(response).toBeDefined();
expect(response.foo).toBeDefined();



回答3:


If you're ok with not using spies, but instead the add-on jasmine-ajax. To mock for a single spec use withMock:

  it("allows use in a single spec", function() {
    var onSuccess = jasmine.createSpy('success');
    jasmine.Ajax.withMock(function() {
      ajax({
            url: 'JSON.php',
            dataType: 'json',           
            onSuccess: onSuccess
      });
      expect(onSuccess).not.toHaveBeenCalled();

      jasmine.Ajax.requests.mostRecent().respondWith({
        "status": 200,
        "responseText": '{"some": "json"}'
      });

      expect(onSuccess).toHaveBeenCalledWith('{"some": "json"}');
    });
  });

The response is only sent when you use respondWith. The link above has some directions how to install



来源:https://stackoverflow.com/questions/8884060/how-to-create-stub-for-ajax-function-using-jasmine-bdd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!