以下jasmine-jquery代码段失败。我得到的错误是"预期的间谍logIt被调用"。
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."
答案 0 :(得分: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
将其删除。