gpt4 book ai didi

javascript - 如何测试 Jasmine 中的方法是否只被调用一次而不是第二次?

转载 作者:行者123 更新时间:2023-11-28 19:39:47 24 4
gpt4 key购买 nike

我正在测试应该调用方法一次并防止任何后续调用 Jasmine 的机制,我可以通过附加断点看到该方法没有被第二次调用但是 Jasmine 测试失败。我认为这与 spy 没有设计用于多次检查有关。
什么是给定情况的适当解决方案?

JSfiddle of Code that is being tested我不知道如何正确地进行 jasmine 测试 jsfiddle(我使用的 Jasmine 版本是 1.3.1,而测试模板是 1.2.0)。

测试看起来像这样:

 it("Invoking OnPreQuery will add event listener for OnTheMoveViewPreLoad event. Triggering OnTheMoveViewPreLoad twice will call getChildrenForMasterRecordList only first time", function () {
AddTreeSettingsObjectToBC({ bc: bc, Tree: { IncludeChildren: true} });
ComposeMockPageObjWithObservableFieldsWithChildren();
var preQuerySpy = spyOnEvent(onTheMove.PageDataRoles, 'OnPreQuery');
$(onTheMove.PageDataRoles).trigger('OnPreQuery', { knockoutContextName: 'bc' });
expect('OnPreQuery').toHaveBeenTriggeredOn(onTheMove.PageDataRoles);
expect(preQuerySpy).toHaveBeenTriggered();
var getChildrenForMasterRecordListSpy = spyOn(window, 'getChildrenForMasterRecordList');
$(onTheMove.PageDataRoles).trigger('OnTheMoveViewPreLoad', { knockoutContextName: 'bc' });
expect(getChildrenForMasterRecordListSpy).toHaveBeenCalled();
$(onTheMove.PageDataRoles).trigger('OnTheMoveViewPreLoad', { knockoutContextName: 'bc' });
expect(getChildrenForMasterRecordListSpy).not.toHaveBeenCalled();
});

正在测试的代码:HTML

<div data-role="page"></div>

Javascript

var onTheMove = function(){};
$.extend(onTheMove,{
NullValue : "null",
PageDataRoles : 'div[data-role="page"], div[data-role="dialog"]',
OnTheMovePrefix : 'OnTheMove_'
});

$(document).on('OnPreQuery', onTheMove.PageDataRoles, function (e, options) {
var isChildAttachmentQueued = true;
var knockoutContextName = options.knockoutContextName;
if (TreeEnabled(knockoutContextName)) {
var isModelReadyToAttachChildren = function () {
var isReady = false;
if (PageObj[knockoutContextName] != undefined) {
isReady = (PageObj[knockoutContextName]().length > 0) && isChildAttachmentQueued;
}

return isReady;
};
var treeSettings = eval(knockoutContextName).Tree;
treeSettings.knockoutContextName = knockoutContextName;
$(onTheMove.PageDataRoles).on('OnTheMoveViewPreLoad', function (e, options) {
if (isModelReadyToAttachChildren()) {
getChildrenForMasterRecordList({
parentTable: eval(knockoutContextName).primaryTableName,
knockoutContextName: treeSettings.knockoutContextName,
parentIdColumn: treeSettings.ParentIdColumn,
masterIdColumn: treeSettings.MasterIdColumn
});
isChildAttachmentQueued = false;
}
});
}
});
function getChildrenForMasterRecordList(options) {
console.log('beep');
}

最佳答案

toHaveBeenCalledTimes(1)

现在让这变得容易多了。

 expect(yourSpy).toHaveBeenCalledTimes(1);

关于javascript - 如何测试 Jasmine 中的方法是否只被调用一次而不是第二次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24159707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com