简体   繁体   中英

“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);

However, when I run any test (using flutter test command) which imports widgets where I have used webSaveAs function, I get the following error:

./../../../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;
^

I am using js: ^0.6.2 from https://pub.dev/packages/js and here is the result from flutter doctor command.

╰>>> 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!

Could someone help me figure this out? Thanks in advance!

Issue:

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. Hence, it will not contain dart:js .


Solution:

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();
}

And then create a new file (let's say shared.dart ) like below.

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 .


Explanation:

dart.library.io is available in Dart VM and dart.library.js is available in web.

In web, if (dart.library.io) is false . Therefore, it will import web.dart which is what we want.

When running tests, if (dart.library.io) is true since the tests run in 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 .


References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM