javascript - 使用 jasmine 进行真正的 ajax 调用

标签 javascript ajax jasmine

我想使用 Jasmine 做两件事,测试执行真正 ajax 调用的函数,并从 ajax 调用获取回调数据以用于其他 jasmine 测试。

这是我到目前为止所拥有的:

Javascript函数:

function getAttributeInfo(selectedLayer){

    // Get layer attributes
    $.ajax({
        type: 'get',
        url: '/geoserver/oqplatform/ows?service=WFS&version=1.0.0&request=GetFeature&typeName='+ selectedLayer +'&outputFormat=json',
        success: function(data) {
            // pass the data into a global variable
            foo = data;
            // EDIT
            return data;
        }
    });
}

测试:

it("an ajax test", function() {

    var ajaxFunction = getAttributeInfo(SVIRLayerNames[0]);
    // creating spied callback
    var callback = jasmine.createSpy('callback');

    spyOn($, 'ajax').and.callFake(function (req) {
        var d = $.Deferred();
        return d.promise();
    });

    // EDIT
    //ajaxFunction.fetch(callback);
    ajaxFunction(callback);

    // everything after this does not seem to execute
    var fakeData = callback.calls.mostRecent().args[0];
});

如果我在 5 秒后通过控制台记录 foo 变量,我可以看到发出了 ajax 请求并且数据在 foo 变量中可用

最佳答案

经过几天的研究,我最大的收获是 Jasmine 是一个很棒的工具,但文档很糟糕。我发现很难简单地理解 spy 是什么以及何时应该使用它。

我的解决方案是根本不使用 spy 。

beforeAll(function(done) {

    var mySyncFunction = function () {

        var layerName = 'foobar';
        var layerRequest = getAttributeInfo(layerName);

        layerRequest.success(function(layerResponse) {
            // Pass data from the response into a global variable to be tests
            // I can also check for things like the API version number.
        });

        layerRequest.done(function() {
           // Alert Jasmine that the AJAX call is done
           done();
        });
    };

    mySyncFunction();
}

在 getAttributeInfo 函数中,我在 $.ajax 之前添加了 return

更新

...
beforeAll(function(done) {
    $.ajax({
        url: '/my/data',
        data: {},
        success: function (response) {
            foo = response
            done();
        },
    dataType: 'html'
    });
});

////////////////
// Some tests //
////////////////

it("meets some requirement", function() {
    for (var i = 0; i < foo.length; i++) {
        var name = foo[i].fields.name;
        expect(name).toBeDefined();
    }
});

关于javascript - 使用 jasmine 进行真正的 ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229267/

相关文章:

使用 Jasmine 进行 Angular 单元测试 - 错误 : Please add an @NgModule annotation

php - 如何在不重复代码的情况下调用多个 AJAX 函数(到 PHP)

javascript - 使用替代 promise 时如何解决 ajax 调用中的错误

javascript - 如何从我的 angular-js 指令中单击函数?

javascript - 如何删除aws s3存储桶中具有相同键的多个对象

php - 使用ajax php mysql的用户通知/警报系统

javascript - 测试 typescript 装饰器

javascript - 如何在我的子 Controller 中模拟此方法来测试它?

javascript - extJs 4 网格自定义 - 最后的总行

javascript - LazyLoad 不隐藏占位符 img Rails 5