Jasmine test.load () to get url

I have a function that loads a template and I want to check the correct url.

Since I cannot find any information other than tracking ajax calls, I assume this is the same for calls .load(). I am using Jasmine 2.4.1

Function

function templateLoader() {
    var templateURL = '/path/to/template.html';
    $('#myElement').load(templateURL, function(response, status, xhr) {
        if (status === "error") {
            common.templateError(templateURL, xhr);
        } else {
            ns.successFunction();
        }
    });
}

Jasmine test

var templateURL = '/path/to/template.html';
spyOn($('#myElement'), "load");
templateLoader(); // call the function
expect($('#myElement').load.calls.mostRecent().args[0]["url"]).toEqual(templateURL);

When I run this test, I get the following error:

TypeError: unable to read property "mostRecent" from undefined

Is there any other way to do this? I also want to verify that the success function is being called, but until you can verify the URL is correct, I cannot do this.

+1
source share
1 answer

:

  • - ajax, spyOn $.ajax $(#myElement).load
  • URL- successCallBack ajax. , successCallback , .
  • , , ajax fakeFunction , , , .

: 2.5

, . ,

function templateLoader(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) {
      return new $.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();
    });
});
+2

All Articles