测试飞镖 ajax HttpRequest

Testing dart ajax HttpRequest

当我尝试测试 post HttpRequest 时,我不太确定我理解发生了什么。这是我的 class 的代码:

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 秒,测试就会顺利通过。

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

您需要 return Future 以便测试可以等待它完成

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

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