DEV Community

Discussion on: Use bind to assert a function throws error

Collapse
 
oysmal profile image
Øystein Malt

Another, maybe more intuitive way to do this in ES2016+ is to pass a lambda function calling the function that should throw. By your example:

assert.throws(() => foo('bar'), "Expected error message");

Gives you the same result :) Anyway, nice post! I know this behavior tripped up many people on my team.

Collapse
 
markomannux profile image
Marco Mannucci

Absolutely! I think even a simple anonymous function would work, but in that case the scope may bite you 😂

Collapse
 
oysmal profile image
Øystein Malt

It wouldn’t in this case, as the function tested would retain its scope. It is functionally the same if you intent to bind the function to itself. In fact bind returns a new function (so you get 2 functions here as well), which is good to remember if using it with e.g. React event handlers (referential equality changes) 😊