Skip to content Skip to sidebar Skip to footer

Jasmine Testing .load() To Get Called Url

I have a function which loads a template and I want to check the correct URL is being called. As I can't find any information other than for spying on ajax calls, I'm presuming it'

Solution 1:

Few Observations:

  • Your load is an ajax function, so you'd have to spyOn$.ajax rather than $(#myElement).load
  • You cannot check both the call URL & the successCallBack at the same time without mocking the ajax function itself. This is because your successCallback gets executed only after you get a response from server, meanwhile your test runs through.
  • Hence the trick is to mock the ajax call itself and call a fakeFunction to resolve the promise, which actually resolves the success value at run-time i.e. synchronously- which aids your expectations.

Note: I used jasmine 2.5

The code below illustrates all the points mentioned above. To see it in action, reach out to the fiddle here

functiontemplateLoader(templateURL) {
  $('#myElement').load(templateURL, null, function(response, status, xhr) {
    if (status === "error") {
      common.templateError(templateURL, xhr);
    } else {
      successFunction();
    }
  });
}

successFunction = function() {
  console.log("This is a success Function");
}

describe("spec to test ajax url", function() {
  it('test load call url', function() {
    spyOn($, 'ajax').and.callThrough();
    spyOn(window, 'successFunction').and.callThrough();
    templateLoader("https://jsonplaceholder.typicode.com/posts/1");
    expect($.ajax.calls.mostRecent().args[0]["url"]).toEqual("https://jsonplaceholder.typicode.com/posts/1");    
  });

  it('test success function', function(){
    spyOn(window, 'successFunction').and.callThrough();
    spyOn($, 'ajax').and.callFake(function(e) {
      returnnew $.Deferred().resolve({}).promise();
    });
    templateLoader("https://jsonplaceholder.typicode.com/posts/1");
    expect($.ajax.calls.mostRecent().args[0]["url"]).toEqual("https://jsonplaceholder.typicode.com/posts/1");    
    expect(window.successFunction).toHaveBeenCalled();
    });
});

Post a Comment for "Jasmine Testing .load() To Get Called Url"