_test_http_request.dart 2.24 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:js_interop';
6

7
import 'package:web/web.dart' as web;
8

9 10
/// Defines a new property on an Object.
@JS('Object.defineProperty')
11
external void objectDefineProperty(JSAny o, String symbol, JSAny desc);
12 13

void createGetter(JSAny mock, String key, JSAny? Function() get) {
14
  objectDefineProperty(
15
    mock,
16
    key,
17 18 19 20
    <String, JSFunction>{
      'get': (() => get()).toJS,
    }.jsify()!,
  );
21 22 23 24 25 26 27
}

@JS()
@staticInterop
@anonymous
class DomXMLHttpRequestMock {
  external factory DomXMLHttpRequestMock({
28 29 30 31 32 33 34
    JSFunction? open,
    JSString responseType,
    JSNumber timeout,
    JSBoolean withCredentials,
    JSFunction? send,
    JSFunction? setRequestHeader,
    JSFunction addEventListener,
35 36 37
  });
}

38 39
typedef _DartDomEventListener = JSVoid Function(web.Event event);

40 41 42
class TestHttpRequest {
  TestHttpRequest() {
    _mock = DomXMLHttpRequestMock(
43 44 45 46
        open: open.toJS,
        send: send.toJS,
        setRequestHeader: setRequestHeader.toJS,
        addEventListener: addEventListener.toJS,
47
    );
48
    final JSAny mock = _mock as JSAny;
49
    createGetter(mock, 'headers', () => headers.jsify());
50
    createGetter(mock,
51
        'responseHeaders', () => responseHeaders.jsify());
52
    createGetter(mock, 'status', () => status.toJS);
53
    createGetter(mock, 'response', () => response.jsify());
54 55 56 57 58 59
  }

  late DomXMLHttpRequestMock _mock;
  MockEvent? mockEvent;
  Map<String, String> headers = <String, String>{};
  int status = -1;
60
  Object? response;
61 62

  Map<String, String> get responseHeaders => headers;
63
  JSVoid open(String method, String url, bool async) {}
64
  JSVoid send() {}
65 66
  JSVoid setRequestHeader(String name, String value) {
    headers[name] = value;
67 68
  }

69 70 71 72
  JSVoid addEventListener(String type, web.EventListener listener) {
    if (type == mockEvent?.type) {
      final _DartDomEventListener dartListener =
          (listener as JSExportedDartFunction).toDart as _DartDomEventListener;
73
      dartListener(mockEvent!.event);
74 75 76
    }
  }

77
  web.XMLHttpRequest getMock() => _mock as web.XMLHttpRequest;
78 79 80 81 82 83
}

class MockEvent {
  MockEvent(this.type, this.event);

  final String type;
84
  final web.Event event;
85
}