javascripttypescriptjestjsspyon

Running several Jest tests when spying the same prototype function


I have some code similar to this:

class A {
    f1() { }
}
function f2() {
    const a = new A();
    a.f1();
}
test('test1', async () => {
    const spy_f1 = jest.spyOn(A.prototype, "f1");
    f2();
    console.log("In test1", spy_f1.mock.calls);
});
test('test2', async () => {
    const spy_f1 = jest.spyOn(A.prototype, "f1");
    f2();
    console.log("In test2", spy_f1.mock.calls);
});

I want to test how many times and with which arguments function f2 calls function f1. To do that I would like to spy function f1. Though, for that, I need the object on which f1 is applied, and that object is local to function f2. So, I cannot.

Another possibility is to spy on the object A.prototype. It works if I run only test1 or only test2. But if I run both, the two tests are not independent on each other. For test2, it appears that f1 is called twice.

Other solutions?


Solution

  • A solution is to keep in different test files all the tests spying on the same prototype.