简体   繁体   English

Dart/Flutter Web 单元测试错误:错误:未找到:'dart:html'

[英]Dart/Flutter Web unit testing errors: Error: Not found: 'dart:html'

I'm working on a Flutter web app and I'm having trouble running a test.我正在开发 Flutter web 应用程序,但在运行测试时遇到问题。

Flutter 1.7.8+hotfix.4 • channel stable • git@github.com:flutter/flutter.git
Framework • revision 20e59316b8 (9 weeks ago) • 2019-07-18 20:04:33 -0700
Engine • revision fee001c93f
Tools • Dart 2.4.0

This is the pubspec.yaml:这是 pubspec.yaml:

name: web_flutter
description: An app built using Flutter for web

environment:
  # You must be using Flutter >=1.5.0 or Dart >=2.3.0
  sdk: '>=2.3.0-dev.0.1 <3.0.0'

dependencies:
  flutter_web: any
  flutter_web_ui: any
  provider: any
  rxdart: ^0.22.0
  http: ^0.12.0+2
  json_annotation: ^2.4.0
  intl: 0.15.8


dev_dependencies:
  build_runner: ^1.4.0
  build_web_compilers: ^2.0.0
  pedantic: ^1.0.0
  json_serializable: ^3.0.0
  test: any

flutter:
  uses-material-design: true

dependency_overrides:
  flutter_web:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web
  flutter_web_ui:
    git:
      url: https://github.com/flutter/flutter_web
      path: packages/flutter_web_ui
  provider:
    git:
      url: https://github.com/kevmoo/provider
      ref: flutter_web

I wrote a couple of tests that are passing when I run pub run test in either the IDE's terminal (VS Code) or in terminal app.当我在 IDE 的终端(VS 代码)或终端应用程序中运行pub run test时,我编写了几个测试通过。

The test I'm having trouble with requires some package imports from the project.我遇到问题的测试需要从项目中导入一些 package。 With this test in place I get errors and the other two tests don't run.有了这个测试,我得到了错误,其他两个测试没有运行。 I haven't found anything that points to a solution.我还没有找到任何指向解决方案的东西。

This is the error message:这是错误消息:

pub run test                                                                                         MyMac@MyMac
00:06 +0 -1: loading test/service_test.dart [E]                                                                                                                          
  Failed to load "test/service_test.dart":
  Unable to spawn isolate: file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/ui.dart:12:8: Error: Not found: 'dart:html'
  import 'dart:html' as html;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:11:8: Error: Not found: 'dart:html'
  import 'dart:html' as html;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web/lib/src/services/asset_bundle.dart:7:8: Error: Not found: 'dart:html'
  import 'dart:html' show HttpRequest;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:12:8: Error: Not found: 'dart:js'
  import 'dart:js' as js;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:13:8: Error: Not found: 'dart:js_util'
  import 'dart:js_util' as js_util;
         ^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/ui/compositing.dart:20:9: Error: Type 'html.Element' not found.
    final html.Element webOnlyRootElement;
          ^^^^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:177:37: Error: Type 'html.NodeTreeSanitizer' not found.
  class _NullTreeSanitizer implements html.NodeTreeSanitizer {
                                      ^^^^^^^^^^^^^^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine.dart:179:21: Error: Type 'html.Node' not found.
    void sanitizeTree(html.Node node) {}
                      ^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine/bitmap_canvas.dart:26:9: Error: Type 'html.Element' not found.
    final html.Element rootElement = html.Element.tag('flt-canvas');
          ^^^^^^^^^^^^
  file:///Users/MyMac/.pub-cache/git/flutter_web-c04fb502b842859de07e36954a9390465a5426c0/packages/flutter_web_ui/lib/src/engine/bitmap_canvas.dart:28:3: Error: Type 'html.CanvasElement' not found.
    html.CanvasElement _canvas;
    ^^^^^^^^^^^^^^^^^^
00:06 +0 -1: Some tests failed.

If I comment out this new test, the errors persist.如果我注释掉这个新测试,错误仍然存在。 If I comment out the test and the related imports the remaining two tests run and pass.如果我注释掉测试和相关的导入,剩下的两个测试运行并通过。

This is the test file (I left the offending code commented out so it's easier for you to see - I hope).这是测试文件(我把有问题的代码注释掉了,这样你更容易看到——我希望如此)。

import 'package:test/test.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'dart:convert';
import 'package:web_flutter/services/service.dart';
// These are the package imports that cause errors:
import 'package:web_flutter/model/model.dart';
import 'package:web_flutter/data/tenant_view_model.dart';

void main(){

  test("getSubmission returns ResponseData{}", () async {
    // Arrange: setup the test
    final _service = Service();

    _service.httpClient = MockClient((request) async {
      final responseData = {
        "id": "some_id",
        "state": "processed",
        "test": true,
        "editable": false,
        "expires_at": "2019-09-19T03:40:22Z",
        "processed_at": "2019-09-12T03:40:22Z",
        "batch_id": "",
        "download_url": "downloadURl.com",
        "permanent_download_url": "permanentdownloadURL.com"
      };
      return Response(json.encode(responseData),200);
    });

    // Act
    final response = await _service.getSubmission("submissionID");

    // Assert
    expect(response.download_url, "downloadURL.com");
  });
  test("generateForm returns SubmissionResponse{}", () async {
    // Arrange: setup the test
    final _service = Service();

    _service.httpClient = MockClient((request) async {
      final submissionResponse = {
        "status": "success",
        "submission": {
          "id": "some_id",
          "state": "pending",
          "test": false,
          "editable": false,
          "expired": false,
          "expires_at": null,
          "metadata": {
            "foo": 123,
            "bar": "baz"
          },
          "processed_at": null,
          "batch_id": null,
          "data_requests": [],
          "download_url": null,
          "permanent_download_url": null
        }
      };
      return Response(json.encode(submissionResponse),200);
    });

    // Act
    final response = await _service.generateForm(42, "templateID");

    // Assert
    expect(response.submission.id, "some_id");
  });

  test('Tenant View Model generateForm returns tenantVM.submission.submission.id', () async {
    // Arrange
    final _service = Service();
    Tenant tenant;
    tenant.id = 42;

    _service.httpClient = MockClient((request) async {
      final submissionResponse = {
        "status": "success",
        "submission": {
          "id": "some_id",
          "state": "pending",
          "test": false,
          "editable": false,
          "expired": false,
          "expires_at": null,
          "metadata": {
            "foo": 123,
            "bar": "baz"
          },
          "processed_at": null,
          "batch_id": null,
          "data_requests": [],
          "download_url": null,
          "permanent_download_url": null
        }
      };
      return Response(json.encode(submissionResponse),200);
    });
    TenantViewModel tenantVM = TenantViewModel(tenant, _service);

    // Act
    await tenantVM.generateForm("templateID");

    // Assert
    expect(tenantVM.submission.submission.id, "some_id");
  });
}

This is the class that has the method I'm trying to test ( generateForm() ).这是 class,它具有我要测试的方法 ( generateForm() )。

import 'package:flutter_web/cupertino.dart';
import 'package:web_flutter/model/model.dart';
import 'package:web_flutter/services/service.dart';

class TenantViewModel with ChangeNotifier {
  Tenant _tenant;
  Property _property;
  Service _service;
  SubmissionResponse _submission;
  ResponseData _responseData;

  TenantViewModel(this._tenant, this._service);

  bool get isNew => _tenant.id == null;

  set tenant(Tenant tenant) {
    if (_tenant != tenant) {
      _tenant = tenant;
      notifyListeners();
    }
  }

  Tenant get tenant => _tenant;

  set property(Property property) {
    _tenant.propertyId = property.id;
    notifyListeners();
  }

  Property get property => _property;

  set submission(SubmissionResponse submission) {
    if (_submission != submission) {
      _submission = submission;
      notifyListeners();
    }
  }

  SubmissionResponse get submission => _submission;

  set responseData(ResponseData responseData) {
    if (_responseData != responseData) {
      _responseData = responseData;
      notifyListeners();
    }
  }

  ResponseData get responseData => _responseData;

  Future generateForm(String templateID) async {
    SubmissionResponse submission;

    submission = await _service.generateForm(_tenant.id, templateID);
    this.submission = submission;

    notifyListeners();
  }

  Future getSubmission(String submissionID) async {
    ResponseData responseData;

    responseData = await _service.getSubmission(submissionID);
    this.responseData = responseData;

    notifyListeners();
  }

  Future save() async {
    Tenant updatedTenant;
    if (tenant.isNew) {
      updatedTenant = await _service.createTenant(_tenant);
      this.tenant = updatedTenant;
    } else {
      updatedTenant = await _service.updateTenant(tenant);
      this.tenant = updatedTenant;
    }
    notifyListeners();
  }

  Future refresh() async {
    if (isNew) {
      return;
    }
    var updatedTenant = await _service.getTenant(_tenant.id);
    if (_tenant.propertyId != null) {
      _property = await _service.getProperty(_tenant.propertyId);
    }
    _tenant = updatedTenant;
    notifyListeners();
  }
}

I have tried: import 'package:flutter_test/flutter_test.dart';我试过: import 'package:flutter_test/flutter_test.dart'; in the test file and adding this to the pubspec.yaml:在测试文件中并将其添加到 pubspec.yaml:

  flutter_test:
    sdk: flutter

These cause their own varieties of errors, because I'm using Flutter Web, not Flutter. Can anyone see where I'm going wrong?这些会导致各种错误,因为我使用的是 Flutter Web,而不是 Flutter。有人能看出我哪里出错了吗?

I am aware that the test I'm working on is probably wrong as it is, but I can't even get to the point of having it run and fail.我知道我正在进行的测试可能是错误的,但我什至不能让它运行并失败。

I had a similar issue while developing for a mobile app, but it turned out that I imported the package dart.html accidentally.我在开发移动应用程序时遇到了类似的问题,但结果是我不小心导入了dart.html包。 I just removed it and I was able to run the program.我刚刚删除它,我能够运行该程序。

由于您正在为使用 dart:html 包的 web 运行颤振测试,因此您必须针对正确的平台。

flutter test --platform chrome

It can happen when you try to import something like @required.当您尝试导入 @required 之类的内容时,可能会发生这种情况。 Then flutter will accidentally put import dart.html above the code.然后flutter会不小心把import dart.html放到代码上面。 Just remove that from the code and then you will fix your issue.只需从代码中删除它,然后您将解决您的问题。

The problem comes because, as my tech lead pointed out, "Unit tests do not have access to dart:html . Unless you run them in the browser."问题的出现是因为,正如我的技术负责人所指出的,“单元测试无法访问dart:html 。除非你在浏览器中运行它们。”

From pub.dev/packages/test:来自 pub.dev/packages/test:

"By default, tests are run in the Dart VM [virtual machine], but you can run them in the browser as well by passing pub run test -p chrome path/to/test.dart . test will take care of starting the browser and loading the tests, and all the results will be reported on the command line just like for VM tests. In fact, you can even run tests on both platforms with a single command: pub run test -p "chrome,vm" path/to/test.dart " “默认情况下,测试在 Dart VM [虚拟机] 中运行,但您也可以通过 pub run test pub run test -p chrome path/to/test.dart在浏览器中运行它们。test 将负责启动浏览器并加载测试,所有结果都会像VM测试一样在命令行上报告。事实上,你甚至可以用一个命令在两个平台上运行测试: pub run test -p "chrome,vm" path/to/test.dart "

To solve my particular problem I ran the tests using pub run test test/print_reports_card_test.dart -p chrome .为了解决我的特定问题,我使用pub run test test/print_reports_card_test.dart -p chrome了测试。

Change import 'dart:html';更改import 'dart:html'; to import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;

and then change pubspec.yaml files dependencies to然后将pubspec.yaml文件依赖项更改为

dependencies:
flutter:
sdk: flutter
http:

and click pub get然后点击pub get

Another solution in case you have tests for both web and mobile is to add @TestOn('browser') at the top of your test file.如果您同时对 Web 和移动设备进行测试,另一种解决方案是在测试文件的顶部添加@TestOn('browser')
Here's the full doc这是完整的文档

I had the exact same issue.我有完全相同的问题。 My problem was that I imported package:url_launcher_web/url_launcher_web.dart which apparently you're not supposed to do.我的问题是我导入了package:url_launcher_web/url_launcher_web.dart显然你不应该这样做。 It was an unused import anyway, so I removed it and then my mobile worked fine.无论如何,这是一个未使用的导入,所以我删除了它,然后我的手机工作正常。

To fix it, remove it and the problem will be solved.要修复它,请将其删除,问题将得到解决。

Why does this error occur : The analyzer produces this diagnostic when an import isn't needed because none of the names that are imported are referenced within the importing library.为什么会发生此错误:当不需要导入时,分析器会生成此诊断信息,因为导入库中没有引用任何导入的名称。

Examples :例子

The following code produces this diagnostic because nothing defined in以下代码会产生此诊断信息,因为在

dart:async

is referenced in the library:在库中引用:

import 'dart:async';

void main() {}

Common fixes :常见修复

If the import isn't needed, then remove it.如果不需要导入,则将其删除。

If some of the imported names are intended to be used, then add the missing code.如果打算使用某些导入的名称,则添加缺少的代码。

In which file you had added import 'dart:html' just remove this and then execute the code again.您在哪个文件中添加了 import 'dart:html' 只需删除它,然后再次执行代码。 I think the problem will be solved.我认为问题会得到解决。 Following this i had solved my problem.在此之后,我解决了我的问题。

removing import 'dart:html';删除导入 'dart:html';

from the file worked for me also changing platform to chrome works从对我有用的文件中也可以将平台更改为 chrome works

在此处输入图像描述

This error sometimes occurs when the language mode is out of place.当语言模式不合适时,有时会发生此错误。 Ensure that the "select language mode" (The yellow circle in the image) is on the right mode.确保“选择语言模式”(图中黄色圆圈)处于正确模式。 For this instance I think should be HTML对于这种情况,我认为应该是 HTML

I had the same problem I removed this line and works!我有同样的问题,我删除了这条线并且可以工作! import 'dart:html'导入“飞镖:html”

You need to do some conditional import and implement the components you accessed in "dart:html" to your own file您需要做一些条件导入并将您在“dart:html”中访问的组件实现到您自己的文件中

Here's an example in a case where I am making use of dart:html 's window.open这是我使用dart:htmlwindow.open的例子

window_service.dart window_service.dart

Window window = Window();

class Window {
  void open(String url, String name, [String? options]) {}
}

with the above you can do:通过以上你可以做到:

import "window_service.dart" if (kIsWeb) "dart:html" as html;
...
html.window.open(url, name, options);

Do the same for every dart:html calls you made by implementing them with similar/same structure in the dummy file (window_service.dart).通过在虚拟文件 (window_service.dart) 中使用相似/相同的结构实现它们,对您进行的每个dart:html调用执行相同的操作。 Then you may now run your tests without error.然后您现在可以无误地运行您的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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