开发者

Jquery ajax load of JSON in unit tests

开发者 https://www.devze.com 2023-02-03 11:38 出处:网络
I\'m trying to load a dataset in jasmine for my tests like such ... However as its a json call I cant seem to always get the test denoted by \"it\" to wait till the JSON call has finished before usin

I'm trying to load a dataset in jasmine for my tests like such ... However as its a json call I cant seem to always get the test denoted by "it" to wait till the JSON call has finished before using its array. I tried using the ajaxStop function to no avail. Any ideas ?

describe("simple checks", function() {

  var exa开发者_如何学PythonmpleArray = new Array();   

beforeEach(function(){

    $(document).ajaxStop(function() {
        $(this).unbind("ajaxStop");

        $.getJSON('/jasmine/obj.json', function(data) {

         $.each( json.jsonattr, function(i, widgetElement) {                     
            exampleArray.push(new widget(widgetElement));
            });
          });
       });

});


  it("use the exampleArray", function() {

    doSomething(exampleArray[0]); // frequently this is coming up as undefined

 });


Instead of using $.getJSON, you could use $.ajax() and set async to false in your parameters, then parse the JSON using .parseJSON():

$.ajax({
    url: '/jasmine/obj.json',
    async: false,
    dataType: 'json',
    success: function(data) {
        var jsonvar = $.parseJSON(data);
        //your code here!

    }
});

I will warn you that setting async to false can cause the browser to appear frozen if the call takes a long time, but it will prevent any other JavaScript or jQuery code from executing until the call is finished and the data is loaded (assuming the call is a success).

0

精彩评论

暂无评论...
验证码 换一张
取 消