1

我有一个加载模板的函数,我想检查是否调用了正确的 URL。

因为除了监视 ajax 调用之外我找不到任何信息,我假设调用是一样的.load()。我正在使用茉莉花 2.4.1

功能

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();
        }
    });
}

茉莉花测试

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

当我运行此测试时,我收到以下错误:

TypeError:无法读取未定义的属性“mostRecent”

有不同的方法可以做到这一点吗?我还想检查是否调用了成功函数,但直到可以检查 URL 是否正确我不能这样做。

4

1 回答 1

2

几个观察:

  • 你的负载是一个ajax函数,所以你必须spyOn $.ajax 而不是$(#myElement).load
  • 如果不模拟 ajax 函数本身,就不能同时检查调用 URL 和 successCallBack。这是因为您的 successCallback 只有在您从服务器获得响应后才会执行,同时您的测试会运行。
  • 因此,诀窍是模拟 ajax 调用本身并调用 fakeFunction 来解决承诺,这实际上在运行时解决了成功值,即同步 - 这有助于您的期望。

注意: 我用的是 jasmine 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();
    });
});
于 2016-12-06T21:45:16.217 回答