Search code examples
javascripttypescriptjestjstest-coverage

Testing of private methods in typescript


Let's say I have the following typescript class:

class MyComponent {
  private something: number;

  constructor () {
    this.something = 0
    this.incrementSomething()
  }

  private incrementSomething () : number {
    return this.something++
  }
}

export default MyComponent

And my goal is to test it with jest, but I've got more questions then answers.

  • Is this a bad design pattern?
  • Should private methods be tested? (there are many opinions on the net, hard to decide)
  • Should I ignore jest coverage with this setup as it will report class as untested?
  • Should I create a public method instead and call my private method within it?

It is my first attempt to use private methods in typescript and try to test them, so please be patient :)


Solution

  • I don't think SO is an ideal place for this kind of question, as most of what you're asking is opinion based. You can however, assert that the object is any in order to do some testing:

    class MyComponent {
      private something: number;
    
      constructor () {
        this.something = 0
        this.incrementSomething()
      }
    
      private incrementSomething () : number {
        return this.something++
      }
    }
    
    const thingIWantToTest = new MyComponent();
    
    console.log((thingIWantToTest as any).something); // works
    console.log(thingIWantToTest.something);          // type error