【问题标题】:Testing dart ajax HttpRequest测试飞镖 ajax HttpRequest
【发布时间】:2016-08-25 01:19:22
【问题描述】:

当我尝试测试 HttpRequest 后,我​​不太确定我是否理解发生了什么。这是我的班级的代码:

import 'dart:html';

class HttpReportAdapter {

  var    logmaster;
  int    log_level = 2;
  String url;

  HttpReportAdapter(this.url) {}

  post(r, level) {

    var data = {
      'message'   : r,
      'log_level' : log_level.toString(),
    };

    if(this.logmaster != null)
     data['log_level_string'] = this.logmaster.log_level_as_string(level);

    return HttpRequest.postFormData(this.url, data);

  }

}

这是测试代码:

import '../lib/report_adapters/http_report_adapter.dart';
import "package:test/test.dart";

void main() {

  var adapter;

  setUp(() {
    adapter = new HttpReportAdapter("http://localhost:4567/errors");
  });

  test("sends an ajax request and acknowledges a 200 response from the server", () {
    adapter.post("message", 2).then((_) => print("!!!!!!!!!"));
  });

}

现在,如您所见,我什至没有尝试测试任何东西,只是输出一些东西。运行此程序时,请求确实发送到http://localhost:4567/errors,我可以在我的服务器日志中看到它。

但是,!!!!!!!! 不会打印出来。 此外,测试失败:

This test failed after it had already completed. Make sure to use 
[expectAsync] or the [completes] matcher when testing async code.

但是,如果我在发送响应之前强制我的服务器休眠 1 秒,则测试通过而不会出现错误。

如果有人能帮助我理解这一切,并因此编写正确的测试,我将不胜感激。

【问题讨论】:

    标签: ajax dart dart-async


    【解决方案1】:

    您需要返回Future,以便测试可以等待它完成

    return adapter.post("message", 2).then((_) => print("!!!!!!!!!"));
    

    否则测试在服务器响应到达之前完成。

    【讨论】:

    • 但是HttpRequest.postFormData 已经返回了一个未来,这就是我从post() 方法返回的内容。 api.dartlang.org/1.14.2/dart-html/HttpRequest/postFormData.html
    • 哦,我明白了,从测试本身返回,明白了。我刚试过,这是我收到一个奇怪输出的错误:[object XMLHttpRequestProgressEvent]
    • 请尝试打印event.target.statusevent.target.statusText,其中eventXMLHttpRequestProgressEvent
    • 恐怕我做不到。我不知道[object XMLHttpRequestProgressEvent] 的输出是什么,我的代码中没有任何打印语句。而且我无法从任何地方得到那个对象,因为我得到的只是一个 Future。
    • 你可以试试这个网址吗? cors-test.appspot.com/test。我在本地尝试了您的代码,它对我来说工作正常。我假设您遇到了 CORS 问题。
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多