Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing a function throws ForbiddenError #945

Open
DoubleJ-G opened this issue Jul 19, 2024 · 1 comment
Open

Testing a function throws ForbiddenError #945

DoubleJ-G opened this issue Jul 19, 2024 · 1 comment

Comments

@DoubleJ-G
Copy link

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
Copy link
Owner

stalniy commented Jul 19, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants