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'.

2
  • I think you should verify the singleton creation. See here stackoverflow.com/a/36978360/6161531 Commented Feb 27, 2020 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. Commented Feb 27, 2020 at 13:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks mate! You made my day. I couldn't handle this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.