[英]“Not found: 'dart:js' export 'dart:js' show allowInterop, allowInteropCaptureThis” error when running tests
In my Flutter app, I have a file called web.dart
and inside it I have webSaveAs
function which saves a file to my local machine in web.
@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);
但是,當我運行任何導入我使用webSaveAs
function 的小部件的測試(使用flutter test
命令)時,我收到以下錯誤:
./../../../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;
^
我正在使用js: ^0.6.2
from https://pub.dev/packages/js ,這是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!
有人可以幫我解決這個問題嗎? 提前致謝!
When you execute flutter test
command, Flutter will compile the code in test files to native Dart and run inside a Dart VM where there is no Javascript support. 因此,它不會包含dart:js
。
You can create a dummy file (let's say web.test.dart
) like below to mock the functions that use package:js
or dart:js
package methods.
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';
When you need to use webSaveAs
function, instead of importing web.dart
file, you should import shared.dart
.
dart.library.io
is available in Dart VM and dart.library.js
is available in web.
在 web 中, if (dart.library.io)
為false
。 因此,它將導入我們想要的web.dart
。
運行測試時, if (dart.library.io)
為true
,因為測試在 Dart VM 中運行。 Hence, it will import web.test.dart
which won't throw any errors since it does not import package:js
or dart:js
.
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.