My current project involves an utility function that exposes a generator:
export class Utility {
// This utility function 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 the binary combination array
yield c;
}
}
}
Now, I am incorporating this generator in my code in the following manner:
myFuncion(input){
const n = numberOfVariables(input);
const binaryCombinations = Utility.binaryCombinationGenerator(n);
let combination: boolean[] = binaryCombinations.next().value;
while (till termination condition is met) {
// Perform actions and check for termination condition
combination = binaryCombinations.next().value;
}
}
During my unit tests (using Jasmine), I aim to monitor how many times the generator function is invoked (i.e., how many combinations are generated) before termination. Below is what I have attempted:
it("My spec", () => {
// Arrange
const generatorSpy = spyOn(Utility, "binaryCombinationGenerator").and.callThrough();
// Act
// Assert
expect(generatorSpy).toHaveBeenCalledTimes(16); // This fails with the message: Expected spy binaryCombinationGenerator to have been called 16 times. It was called 1 time.
});
However, the assertion fails since binaryCombinationGenerator
is only called once. What I truly intend to spy on is the next
method of IterableIterator
.
Yet, I am uncertain about how to achieve this. Any suggestions would be appreciated.