[英]How to spy on static generator functions?
我有一個公開生成器的實用程序函數:
export class Utility {
// provides a generator that streams 2^n binary combinations for n variables
public static *binaryCombinationGenerator(numVars: number): IterableIterator<boolean[]> {
for (let i = 0; i < Math.pow(2, numVars); i++) {
const c = [];
//fill up c
yield c;
}
}
}
現在,我在代碼中使用此生成器,如下所示:
myFuncion(input){
const n = numberOfVariables(input);
const binaryCombinations = Utility.binaryCombinationGenerator(n);
let combination: boolean[] = binaryCombinations.next().value;
while (till termination condition is met) {
// do something and check whether termination condition is met
combination = binaryCombinations.next().value;
}
}
在我的單元測試(使用Jasmine)中,我想驗證終止之前調用生成器函數的次數(即生成了多少組合)。 以下是我嘗試過的方法:
it("My spec", () => {
//arrange
const generatorSpy = spyOn(Utility, "binaryCombinationGenerator").and.callThrough();
//act
//assert
expect(generatorSpy).toHaveBeenCalledTimes(16); // fails with: Expected spy binaryCombinationGenerator to have been called 16 times. It was called 1 times.
});
但是,此聲明失敗,因為確實會一次調用binaryCombinationGenerator
。 我實際上想監視的是IterableIterator
的next
方法。
但是,我不確定該怎么做。 請提出建議。
您可以從Utility.binaryCombinationGenerator
方法返回一個茉莉花間諜對象
let binaryCombinationsSpy = jasmine.createSpyObject('binaryCombinations', ['next']);
binaryCombinationsSpy.next.and.returnValues(value1, value2);
spyOn(Utility, "binaryCombinationGenerator").and.returnValue(binaryCombinationsSpy);
expect(binaryCombinationsSpy.next).toHaveBeenCalledTimes(2);
我將其發布為答案,因為這是我模擬生成器函數所做的。 這是基於@ 0mpurdy的答案 。
為了模擬生成器函數,我們實際上需要調用一個偽函數,該函數將為生成器函數的next()
的每次調用提供不同的值(並且在適用時受限制)。
可以通過以下方法簡單地實現:
//arrange
const streamSpy= jasmine.createSpyObj("myGenerator", ["next", "counter"]);
streamSpy.counter = 0;
const values = [{ value: here }, { value: goes }, { value: your }, { value: limited },
{ value: values }]; // devise something else if it is an infinite stream
// call fake function each time for next
streamSpy.next.and.callFake(() => {
if (streamSpy.counter < values.length) {
streamSpy.counter++;
return values[streamSpy.counter - 1];
}
return { value: undefined }; // EOS
});
spyOn(Utility, "myGenerator").and.returnValue(streamSpy);
...
//assert
expect(streamSpy.next).toHaveBeenCalledTimes(2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.