std assertThrows is acting like assertThrowsError
See original GitHub issueI just started building everything in Deno - even when node is the target (after a bundle and some creative imports). Absolutely love it.
I found something that seems odd to me in std / assert. I would like to make a PR for it, but first I would like to hear if there is a (good) reason it is currently implemented like this.
The assertThrows
as described in https://deno.land/manual/testing/assertions
is documented as if it asserts that “something” is being thrown. Yet
Deno.test('Naming is hard',()=>{
assertThrows(()=>{
throw "msg"
})
})
returns AssertionError: A non-Error object was thrown.
. You will have to return a proper Error
to get a pass
Deno.test('Naming is hard',()=>{
assertThrows(()=>{
throw Error("msg")
})
})
On MDN the throw statement is defined as
It seems odd to demand a thrown exception is of a specific type (Error
) when the name assertThrows
indicates that it is testing if something is thrown.
I suggest that the current behaviour gets renamed to assertThrowsError
and assertThrows
is changed to disregard what type is thrown (also it’s async sibling).
Let me know if there is some hidden knowledge or good reasons for the current behaviour. And if that is the case I’m happy to make a PR to the docs repo to explain it better to the next dev coming along this path of the world of Deno.
I do understand that it is a breaking change, but better to sort out consistency early than carrying confusion into the future… right? If not, maybe a way forward would be to add assertThrowsException
to verify that an exception was thrown but disregard the type.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:3
- Comments:14 (14 by maintainers)
I think this issue is still valid. From my understanding, what this issue suggests is removing the below 3 lines from
assertThrows
:https://github.com/denoland/deno_std/blob/6212e9021f7533f106558721909315cf8639de0a/testing/asserts.ts#L682-L684
My PR doesn’t solve this, it will just make this change easier. assertThrows and assertRejects will still do error assertions by calling assertError. If it gets merged, all you would have to do is make assertThrows and assertRejects not call assertError if
typeof errorCallback == "function"
. I think it would make sense to have assertThrows and assertRejects also not call assertError when the only argument is fn.I think if both those changes were made,
assertThrows(fn)
could be used to just check if anything was thrown,assertThrows(fn, Error, msg)
could be shorthand for calling assertError on the value that is thrown, then with a callback likeassertThrows(fn, (e) => assertEquals(e, "Fail"))
could be used to make custom assertions on the value that was thrown.