unittests/tests/dataloader.js
branchnew-model
changeset 924 64c2eaafe5e2
parent 923 b3ee7d1b472a
child 925 28efc97b5d78
equal deleted inserted replaced
923:b3ee7d1b472a 924:64c2eaafe5e2
     1 function test_dataloader() {
       
     2   module("Dataloader", { setup: function() {                                     
       
     3                                       IriSP.jQuery = jQuery;
       
     4                                 }
       
     5     });  
       
     6   
       
     7   test("should initialize dataloader", function() {
       
     8     var dt = new IriSP.DataLoader();    
       
     9     deepEqual(dt._cache, {}, "_cache empty");
       
    10   });
       
    11                
       
    12   test("should get an outside ressource", function() {
       
    13    
       
    14     var response_array = [{ id: 12, text: "Hey there" }];
       
    15     var response_string = JSON.stringify(response_array);
       
    16     
       
    17     var xhr = this.sandbox.useFakeXMLHttpRequest();
       
    18     var requests = this.requests = [];
       
    19     
       
    20     xhr.onCreate = function (request) {
       
    21         requests.push(request);
       
    22     };
       
    23 
       
    24     var spy_callback = this.spy();
       
    25     var dt = new IriSP.DataLoader();
       
    26     
       
    27     var resp = dt.get("/url&a=1", spy_callback);
       
    28 
       
    29     equals(xhr.requests.length, 1, "the mock ajax object should have received the request");
       
    30     
       
    31     xhr.requests[0].respond(200, { "Content-Type": "application/json" },
       
    32                              response_string);
       
    33     
       
    34     
       
    35     ok(spy_callback.calledOnce, "callback called");
       
    36     ok(spy_callback.calledWith(response_array), "callback called with correct string");
       
    37     
       
    38     deepEqual(dt._cache["/url"], response_array, "the response should be stored in the cache");
       
    39     
       
    40     var resp2 = dt.get("/url&a=2", spy_callback);
       
    41     ok(spy_callback.calledTwice && xhr.requests.length === 1, "callback called twice but request made only once.");
       
    42     
       
    43   });
       
    44  
       
    45   test("should default to JSONP for foreign domains", function() {
       
    46     /* we can't simulate jsonp so we just verify that the function is called */
       
    47     var stub = this.stub(IriSP.jQuery, "ajax");
       
    48     var dt = new IriSP.DataLoader();
       
    49     
       
    50     var resp = dt.get("http://example.com/url&a=1", stub);
       
    51 
       
    52     ok(stub.calledOnce, "ajax request actually made");
       
    53   });
       
    54    
       
    55 }