How to assert warnings? #3339
Unanswered
oscarmarcelo
asked this question in
Q&A
Replies: 1 comment 2 replies
-
I'd venture the event is emitted asynchronously, so your hooks are not capturing them. Instead make your test wait for the next warning: import { once } from 'node:events'
import process from 'node:process'
import test from 'ava'
test('test warning', async t => {
const next = once(process, 'warning')
fn()
const warning = await next
t.deepEqual(warning, …)
}) Of course this assumes nothing else is emitting warnings. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Asserting errors is pretty straightforward, as we all know, but... how can I assert warnings properly?
Here's two approaches I tried:
Overriding
console.warn
to throw anError
insteadThis was pretty easy. Just monkeypatched
console.warn
to throw errors and then asserted them:But I don't think this to be a good solution, because it will catch just the first "warning", and since a warning should not break, I can't assert for any subsequent warnings or even result/output of the code I'm testing.
Use
emitWarning
and collect their messages through thewarning
eventI believe using
process.emitWarning
is better than usingconsole.warn
in a Node package, as we get much more functionality, including events and command-line flags.But, I'm currently stuck on this one, and honestly I don't know if it's still the best solution, or if we can do something better.
I'm trying to add/remove a listener to the
warning
event to collect all the warnings to awarning
usingbeforeEach
andafterEach
hooks, and then compare the warnings in the test itself:My issue here is that I can't get the warning messages in time. The test finishes before the event callback runs.
Also, I don't think I can monkeypatch
emitWarning
to silence the warnings to avoid noise in the middle of AVA's terminal output...So, how can I make this work? Am I doing this entirely wrong?
Beta Was this translation helpful? Give feedback.
All reactions