2013-07-26 35 views
0

我想使用茉莉花測試「addGroup」函數。我收到以下錯誤:茉莉花調用函數與阿賈克斯返回值

錯誤:預計spy modifyMyHtml被調用.at null。

我不知道測試addGroup函數的最佳方法是什麼。請幫助.....

var myRecord = { 

    addGroup: function(groupNumber) { 

     $.when(myRecord.getHtml()) 
     .done(function(returnedHtml){ 
      myRecord.modifyMyHtml(returnedHtml);   
     }); 
    }, 

    getHtml: function() { 
     return $.ajax({url: "myHtmlFile.html", dataType: "html" }); 
    }, 
    // adds options and events to my returned HTML 
    modifyMyHtml: function(returnedHtml) { 
     $('#outerDiv').html(returnedHtml); 
     var myOptions = myRecord.getOptions(); 
     $('#optionsField').append(myOptions); 
     myRecord.bindEventsToDiv(); 
    }, 
} 

==== JASMINE TEST

describe("Configure Record page", function() { 
    var fixture; 

    jasmine.getFixtures().fixturesPath = "/test/" ; 
    jasmine.getFixtures().load("myHtmlFile.html"); 
    fixture = $("#jasmine-fixtures").html(); 

    describe("addGroup", function(){ 
     beforeEach(function() { 
      var groupNumber = 0; 
      spyOn(myRecord, "getHtml").andCallFake(function(){ 
       return $.Deferred().promise(); 
      }); 
      spyOn(myRecord, "modifyMyHtml"); 
      myRecord.addGroup(groupNumber); 
     }); 

     it("Should call getHtml", function() { 
      expect(myRecord.getHtml).toHaveBeenCalled(); 
     }); 

     it("Should call modifyMyHtml", function() {    
      expect(myRecord.modifyMyHtml).toHaveBeenCalled(); ==>FAILS 
     });   
    }); 
}); 

回答

1

你必須在你andCallFake返回EM之前解決的承諾。

spyOn(myRecord, "getHtml").andCallFake(function(){ 
    return $.Deferred().resolve().promise(); 
}); 

Btw。你不應該測試你想要測試的對象上的函數被調用,但是DOM中的html設置爲正確的html

it("Should call modifyMyHtml", function() {  
    spyOn(myRecord, "getHtml").andCallFake(function(){ 
     return $.Deferred().resolveWith(null, 'returnedHtml').promise(); 
    });   
    expect($('#outerDiv').html).toEqual('returnedHtml') 
}); 
+0

非常感謝。這幫了我很多! – user2624124