gpt4 book ai didi

angular - karma : How to handle multiple calls to a spy that have different responses?

转载 作者:太空狗 更新时间:2023-10-29 19:29:44 25 4
gpt4 key购买 nike

我有一个要测试的方法,在我为两个单独的元素调用 document.getElementById 的方法中。过去,我只是在 document.getElementById 方法上创建了一个 spy ,并将返回值设置为我选择的模拟元素。但是,现在我需要第一次调用 spy 程序以返回一个模拟元素,而下一次调用以返回第二个唯一元素,我不确定如何完成此操作。

代码隐藏:

private scrollParentToChild(): void {
let parent: HTMLElement = document.getElementById('.theParent');
let child: HTMLElement = document.getElementById('.theChild');
parent.scrollTop = child.offsetTop;
}

单元测试:

describe('scrollParentToChild', () => {
it('should set the parents scrollTop to the offsetTop of the child', () => {
let parent: any = {
scrollTop: 0
};
let child: any = {
offsetTop: 100
};
spyOn(document, 'getElementById').and.returnValue(parent); // Okay this will return the parent for both calls to document.getElementById now, but how do I make it only return this for the first call and then return child for the second call.
component.scrollParentToChild();
expect(parent.scrollTop).toEqual(child.offsetTop);
}
});

最佳答案

只要您使用的是相对较新版本的 Jasmine(至少 2.4),您应该能够利用 Jasmine 上的 .and.returnValues(...) 方法 spy 。您可以按如下方式使用它:

spyOn(document, 'getElementById').and.returnValues(parent, child); //note the 's'!

这样,第一次调用getElementById会返回parent,第二次会返回child,后续调用会返回 >未定义

Jasmine docs for returnValues

关于angular - karma : How to handle multiple calls to a spy that have different responses?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281887/

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