"Not found: 'dart:js' export 'dart:js' show allowInterop, allowInteropCaptureThis" 测试 运行 时出错

"Not found: 'dart:js' export 'dart:js' show allowInterop, allowInteropCaptureThis" error when running tests

在我的 Flutter 应用程序中,我有一个名为 web.dart 的文件,在该文件中我有 webSaveAs 功能,可将文件保存到我在网络中的本地计算机。

@JS()
library main;

import 'package:js/js.dart';
import 'package:universal_html/html.dart';

/// Annotate `webSaveAs` to invoke JavaScript `window.webSaveAs`
@JS('webSaveAs')
external void webSaveAs(Blob blob, String fileName);

但是,当我 运行 任何测试(使用 flutter test 命令)在我使用 webSaveAs 函数的地方导入小部件时,我收到以下错误:

./../../../development/flutter/.pub-cache/hosted/pub.dartlang.org/js-0.6.3-nullsafety.3/lib/js.dart:8:1: Error: Not found: 'dart:js'
export 'dart:js' show allowInterop, allowInteropCaptureThis;
^

我正在使用 https://pub.dev/packages/js 中的 js: ^0.6.2,这是 flutter doctor 命令的结果。

╰>>> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 1.25.0-8.3.pre, on macOS 11.2.1 20D74 darwin-x64, locale en-SG)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.3.1)
[✓] VS Code (version 1.53.2)
[✓] Connected device (1 available)

• No issues found!

有人可以帮我解决这个问题吗?提前致谢!

问题:

当您执行 flutter test 命令时,Flutter 会将测试文件中的代码编译为原生 Dart 和 运行 在没有 Javascript 支持的 Dart VM 中。因此,它不会包含 dart:js.


解决方案:

您可以像下面这样创建一个虚拟文件(比方说 web.test.dart)来模拟使用 package:jsdart:js 包方法的函数。

web.test.dart

import 'package:universal_html/html.dart';

void webSaveAs(Blob blob, String fileName) {
  // You can remove the below line below and include your own implementation if you need
  throw UnimplementedError();
}

然后像下面这样创建一个新文件(比方说 shared.dart)。

shared.dart

export 'web.dart' if (dart.library.io) 'web.test.dart';

当你需要使用webSaveAs功能时,不要导入web.dart文件,你应该导入shared.dart.


解释:

dart.library.io 在 Dart VM 中可用,dart.library.js 在 Web 中可用。

在网络中,if (dart.library.io)false。因此,它将导入我们想要的 web.dart

当 运行ning 测试时,if (dart.library.io)true,因为在 Dart VM 中测试 运行。因此,它将导入 web.test.dart 而不会引发任何错误,因为它不会导入 package:jsdart:js.


参考文献: