test: improve unexpected warnings error

If someone adds an `expectsWarning` listener without handling all
warning triggered in that test file, it'll result in a cryptic error
message. This improves the situation by providing an explicit error
about the unexpected warning.

PR-URL: https://github.com/nodejs/node/pull/28138
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Ruben Bridgewater 2019-05-20 00:35:36 +02:00 committed by Rich Trott
parent c1f0cbe961
commit 18a8eec378

View File

@ -528,7 +528,15 @@ let catchWarning;
function expectWarning(nameOrMap, expected, code) {
if (catchWarning === undefined) {
catchWarning = {};
process.on('warning', (warning) => catchWarning[warning.name](warning));
process.on('warning', (warning) => {
if (!catchWarning[warning.name]) {
throw new TypeError(
`"${warning.name}" was triggered without being expected.\n` +
util.inspect(warning)
);
}
catchWarning[warning.name](warning);
});
}
if (typeof nameOrMap === 'string') {
catchWarning[nameOrMap] = _expectWarning(nameOrMap, expected, code);