我有一个要测试的方法,在我为两个单独的元素调用 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
,后续调用会返回 >未定义
。
关于angular - karma : How to handle multiple calls to a spy that have different responses?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281887/