【问题标题】:Jasmine use it to over ride and test a method that uses aiaxJasmine 使用它来覆盖和测试使用 aiax 的方法
【发布时间】:2013-03-22 16:31:38
【问题描述】:

我有一个包含许多方法的 JS 文件,ajax 调用者是常量。

function ajaxCaller(data,url,callback) { //standard jquery ajax call here } 

function method1(){ 
// ... does work ... then 
ajaxCaller(data,url,function(){ // changes the dom } ); 
}

如何使用 jasmine 覆盖 ajaxCaller 方法,该方法几乎被我的 js 文件中的每个方法调用,以便我可以测试 DOM 是否正在发生变化?

【问题讨论】:

    标签: ajax testing jasmine


    【解决方案1】:

    可能你有类似下面的代码,对吧?

    function ajaxCaller(data, url, callback) {
        $.ajax(url, { data: data, success: callback });
    }
    

    在这种情况下,您可以模拟 jQuery ajax 方法,以便调用您提供的函数而不是真正的 AJAX 请求。可以定义您希望“从服务器返回”的response。 Jasmine andCallFake 函数将为您完成:

    it ('when some response returned from the server, something happens', function() {
        var response = {}; // ... define the response you need
        spyOn($, 'ajax').andCallFake(function(url, options) {
            options.success(response);
        });
    
        method1();
    
        // and assert that something really happens ...
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 2020-04-03
      • 2019-12-26
      • 2018-11-04
      • 2021-11-29
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多