简体   繁体   中英

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:)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM