2

我想window.location.reload使用 qunit 成功模拟对象以获取以下功能:

function Test() {
    $.ajax({
        type: 'POST',
        url: /Test/TestMethod,
        data: 1,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8;',
        success: function (response) {
            if (response.Successful)
                window.location.reload();
        },
        error: function (response) {
        }
    });
}

谁能帮我嘲笑这种和平的代码。提前致谢。

4

1 回答 1

2

由于它是 JavaScript,因此您可以覆盖所有函数和对象。为了使事情更容易,我会将您的函数传递给window要使用的对象。这样您就可以注入一个模拟窗口以用于您的测试。如果您在生产中使用代码,您可以传递真实window对象或直接调用不带第二个参数的函数。当您省略参数时,该行var currentWindow = currentWindow || window;确保使用全局窗口。回调也是如此,如果你不指定它,它只是被一个空函数替换。

因为要测试异步调用,所以应该使用asyncTest()QUnit。这使您能够在 AJAX 调用返回时运行测试代码。您所要做的就是在您的代码中添加一个回调参数。对于您的测试,您只需传递一个带有测试代码和模拟窗口的回调方法。通过定义预期断言的expect(2)数量reload()

测试功能:

function ajaxCall(callback, currentWindow) {
    var callback = callback || function() {};
    var currentWindow = currentWindow || window;
    $.ajax({
        type: 'GET',
        url: '/',
        data: 1,
        dataType: 'html',
        success: function (response, statusCode) {
            if (statusCode === "success") {
                currentWindow.location.reload();
            }
            callback(statusCode);
        },
        error: function (response, statusCode) {
            callback(statusCode);
        }
    });
}

window嘲笑:

module("AjaxTests", {
  setup: function() {
      this.mockWindow = {
          location: {
              reload: function() {
                  ok(true, "This mock function should be called");
              }
          }
      };
  }
});

考试:

asyncTest("ajaxCall with mock window", function () {
    expect(2);
    var testCallback = function(statusCode) {
        ok(statusCode === "success", "Response should be successful");
        start();
    }
    ajaxCall(testCallback, this.mockWindow);
});

您可以在 jsFiddle 上看到此代码(这就是为什么我不得不稍微调整您的代码的原因)。

于 2013-02-11T23:59:54.253 回答