How to stub a private class method written in typescript using sine

I am writing unit tests for a public method, which in turn calls a private class method written in typescript (Node JS).

Code example

class A {
   constructor() {  
   }
   public method1() {  
       if(this.method2()) {
          // Do something
       } else {
          // Do something else
       }
   }
   private method2() {
      return true;
   }
}

Now to test method1 () I need to stub method2 (), which is a private method.

here is what i am trying:

sinon.stub(A.prototype, "method2");

Typescript throws an error:

Argument of type '"method2"' is not assignable to parameter of type '"method1"'

Any help would be greatly appreciated. Thank you.

+4
source share
1 answer

The problem is that the definition for sionuses this definition for the function stub:

interface SinonStubStatic { <T>(obj: T, method: keyof T): SinonStub; }

, () T. , , , .

, any:

sinon.stub(A.prototype, <any>"method2");
+3

Source: https://habr.com/ru/post/1689687/


All Articles