0

I have a following problem. I have a singleton class. There is a getInstance static method which call constructor. singleton.ts:

class Singleton {
   private static singletonInstance: Singleton;
   private constructor(){
      ...doSomething;
   }
   public static getInstance(): Singleton {
      if(!Singleton.singletonInstance){
          Singleton.singletonInstance = new Singleton();
      }
      throw new Error('stupid error');
   }
}

singleton.spec.ts:

it('getInstance should throw an error', () => {
   expect(Singleton.getInstance()).toThrow(new Error('stupid error'));
})

'getInstance should throw an error' is failing, because... getInstance() didn't throw the error.

On console output I can notice the error was throw - it prints 'stupid error'.

Banan
  • 3
  • 1
  • 5
  • I think you should verify the singleton creation. See here https://stackoverflow.com/a/36978360/6161531 – Jeppe Hasseriis Feb 27 '20 at 12:39
  • Jeppe, thank you for your comment. It is just example. Of course my singleton class check if instance already exist. I updated my example code for not confusing another users. – Banan Feb 27 '20 at 13:29

1 Answers1

3

As per the example mentioned in the docs here, you need to supply an anonymous function to test this:

it('getInstance should throw an error', () => {
   expect(() => Singleton.getInstance()).toThrow(new Error('stupid error'));
})

Basically, jest calls the given function, and then determines whether it threw an error or not. In your case, since Singleton.getInstance() has already thrown the error, the result is not callable.

31piy
  • 23,323
  • 6
  • 47
  • 67