0

我想使用 Jasmine 测试“addGroup”功能。我收到以下错误:

错误:预期的间谍 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();
    },
}

====茉莉花测试

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
        });         
    }); 
});
4

1 回答 1

1

您必须先解决承诺,然后再将 em 返回到andCallFake.

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

顺便提一句。你不应该测试你想要测试的对象上的函数是否被调用,但 DOM 中的 html 是否设置了正确的 html

it("Should call modifyMyHtml", function() {    
   spyOn(myRecord, "getHtml").andCallFake(function(){
      return $.Deferred().resolveWith(null, 'returnedHtml').promise();
   });         
   expect($('#outerDiv').html).toEqual('returnedHtml')
});   
于 2013-07-27T11:31:23.777 回答