2015-04-22 26 views
0

以下jasmine-jquery代码片段失败。我得到的错误是“期望的间谍日志已被调用”。Spin on Jasmine-jquery函数调用

var logIt = function() { 
    console.log("logged"); 
}; 

$('#id1').on({ 
    click: logIt 
}); 

describe("Clicking id1", function() { 
    it("logs to the console.", function() { 
     spyOn(window, 'logIt'); 
     $('#id1').click(); 
     expect(window.logIt).toHaveBeenCalled(); 
    }); 
}); 

//ERROR: "Expected spy logIt to have been called." 

回答

1

试试这个:

describe("Clicking id1", function() { 
    var logIt, $button; 

    beforeAll(function() { 
     logIt = jasmine.createSpy('logIt() spy'); 

     $button = $('#id1'); 
     $button.click(logIt); 
     $button.click(); 
    }); 

    it("logs to the console.", function() { 
     expect(logIt).toHaveBeenCalled(); 
    }); 
}); 

我在下面跑在我的项目的测试和它的工作:

describe("Clicking id1", function() { 
    var $button, specHelper, logIt; 

    beforeAll(function() { 
     logIt = jasmine.createSpy('logIt() spy'); 
     $button = $('<button>').attr("id", "id1"); 
     specHelper = new SpecHelper(); 
     specHelper.publish($button); 

     $button.click(logIt); 
     $button.click(); 
    }); 

    afterAll(function() { 
     specHelper.conceal($button); 
    }); 

    it("logs to the console.", function() { 
     console.dir(logIt); 
     expect(logIt).toHaveBeenCalled(); 
    }); 
}); 

specHelper.publish附加jQuery的节点到DOM和specHelper.conceal删除。

+0

这会生成相同的评论。 – George

+0

我测试了上述代码的改编版本,它适用于我...你的jasmine-html页面上是否有'id =“id1”'html元素?如果不是,这将导致评论。 – marcel

+0

行 - 你的作品一旦我添加了“id1”的元素。但即使添加元素,我使用'spyOn'的原始测试失败。你知道这是为什么吗? – George