stalniy / casl

CASL is an isomorphic authorization JavaScript library which restricts what resources a given user is allowed to access
https://casl.js.org/
MIT License
5.87k stars 265 forks source link

Testing a function throws ForbiddenError #945

Open DoubleJ-G opened 1 month ago

DoubleJ-G commented 1 month ago

Is your feature request related to a problem? Please describe.

I want to be able to test that a function throws a ForbiddenError. Take this snippet for example:

expect(() =>
  ForbiddenError.from(ability).throwUnlessCan('read', 'Client'),
).toThrow(ForbiddenError);

Currently this is not possible due to the private constructor jest will complain with the following.

Argument of type 'typeof ForbiddenError' is not assignable to parameter of type 'string | RegExp | Constructable | Error | undefined'.
Type 'typeof ForbiddenError' is not assignable to type 'Constructable'.
Cannot assign a 'private' constructor type to a 'public' constructor type.

Describe alternatives you've considered (optional) You can test that the function throws any error with .toThrow() but this isn't precise. In the example above it's the only thing that can throw but in other places I have multiple things to throw and only want to test for ForbiddenError in some tests

Is there a reason for the constructor of this Error to be private? Or is there any alternative to testing that the function throws this type of error?

stalniy commented 1 month ago

constructor is designed to be private in order to enforce usage via .from factory function.

Probably nothing can be done except type casting at the moment. I was not aware about this limitation. I’ll take a look a bit later and very likely just will make it public