recordConsoleLogsAsync function

FutureOr<List<String?>> recordConsoleLogsAsync(
  1. Future asyncCallback(), {
  2. ConsoleConfiguration configuration = allConfig,
  3. bool shouldResetPropTypesWarningCache = true,
})

Captures console logs created during the runtime of a provided asynchronous callback.

The core logic and parameters are the same as those for recordConsoleLogs, with the exception being the provided callback should be asynchronous.

Related: recordConsoleLogs

Implementation

FutureOr<List<String?>> recordConsoleLogsAsync(
  Future Function() asyncCallback, {
  ConsoleConfiguration configuration = allConfig,
  bool shouldResetPropTypesWarningCache = true,
}) async {
  var 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 {
    await asyncCallback();
  } 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;
}