recordConsoleLogs function
- dynamic callback(), {
- ConsoleConfiguration configuration = allConfig,
- bool shouldResetPropTypesWarningCache = true,
Runs a provided callback and returns the logs that occur during the runtime of that function.
Can be used to capture logs, warnings, or errors as specified by setting
the configuration
. To set the configuration
, pass in the corresponding
config class (logConfig, warnConfig, errorConfig, allConfig).
By default, the function assumes that any propType
warnings that occur during
the function runtime should be captured. Consequently, the PropType
cache
is reset prior to calling the provided callback. If you wish to ignore the
propType
warnings that have occurred outside the scope of the callback,
set shouldResetPropTypesWarningCache
to false
.
If any errors are thrown during the callback, e.g. during a render that expects props that are not valid, the errors will be caught to allow the test to complete.
To handle asynchronous behavior, see recordConsoleLogsAsync.
Implementation
List<String?> recordConsoleLogs(
Function() callback, {
ConsoleConfiguration configuration = allConfig,
bool shouldResetPropTypesWarningCache = true,
}) {
final consoleLogs = <String?>[];
final logTypeToCapture = configuration.logType == 'all'
? ConsoleConfiguration.types
: [configuration.logType];
Map<String, JsFunction> consoleRefs = {};
if (shouldResetPropTypesWarningCache) _resetPropTypeWarningCache();
for (var config in logTypeToCapture) {
consoleRefs[config] = context['console'][config];
context['console'][config] =
JsFunction.withThis((self, [message, arg1, arg2, arg3, arg4, arg5]) {
// NOTE: Using console.log or print within this function will cause an infinite
// loop when the logType is set to `log`.
consoleLogs.add(message);
consoleRefs[config]!
.apply([message, arg1, arg2, arg3, arg4, arg5], thisArg: self);
});
}
try {
callback();
} catch (_) {
// No error handling is necessary. This catch is meant to catch errors that
// may occur if a render fails due to invalid props. It also ensures that the
// console is reset correctly, even if the callback is broken.
} finally {
for (var config in logTypeToCapture) {
context['console'][config] = consoleRefs[config];
}
}
return consoleLogs;
}