Why Jest’s toThrow won’t work when create an instance of a ES6 class directly in the constructor?

Here

expect(new TestObject()).toThrow();

new TestObject() is evaluated first, then expect(...), then ...toThrow(), in accordance with operator precedence. When new TestObject() throws, anything else doesn’t matter.

This is why toThrow expects a function that is supposed to throw:

expect(() => {
  new TestObject();
}).toThrow();

This way it can be wrapped with try..catch internally when being called.

It works similarly in Jasmine toThrow and Chai to.throw assertions as well.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)