Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub a private method of a class written in typescript using sinon

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

Sample Code

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 what I am trying :

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

Typescript is throwing the error :

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

Any help would be appreciated. Thank You

like image 945
SHRUTHI BHARADWAJ Avatar asked Nov 22 '17 10:11

SHRUTHI BHARADWAJ


People also ask

Does TypeScript have private methods?

TypeScript Private MethodsMethods can also be private which is useful for hiding implementation detail of how a Class works to the user of the Class.

How does Sinon stub work?

The sinon. stub() substitutes the real function and returns a stub object that you can configure using methods like callsFake() . Stubs also have a callCount property that tells you how many times the stub was called. For example, the below code stubs out axios.

How do you mock a variable in Sinon?

var sinon = require('sinon'); var start_end = require('./start_end'); describe("start_end", function(){ before(function () { cb_spy = sinon. spy(); }); afterEach(function () { cb_spy. reset(); }); it("start_pool()", function(done){ // how to make timer variable < 1, so that if(timer < 1) will meet start_end.


1 Answers

The problem is that the definition for sinon uses the following definition for the stub function :

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

This means that the second parameter must be the name of a member (a public one) of the T type. This is probably a good restriction generally, but in this case it is a bit too restrictive.

You can get around it by casting to any:

sinon.stub(A.prototype, <any>"method2"); 
like image 142
Titian Cernicova-Dragomir Avatar answered Sep 24 '22 03:09

Titian Cernicova-Dragomir