Manuel
Manuel

Reputation: 167

make async method await an event with Dart

I want to test if a method fires an event. If the event was fired synchronously the test method would look something like this:

stringBindable_input_firesEvent() {
  iBindable str = BindableFactory.fromType(Types.String_);
  bool wasTriggered = false;
  str.onChangeForGui.listen((v) {
    wasTriggered = true;
  });
  str.input("test"); //this triggers the event
  expect(wasTriggered, isTrue);
}

Since the event is fired async I need to await it to be fired. How would I go about it?

Upvotes: 1

Views: 58

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

If you only want to test a single event, you can use expectAsync1

  str.onChangeForGui.listen(expectAsync1((v) {
    wasTriggered = true;
  }));

The test will fail if expectAsync1 wasn't called before the test times out.

For more complex scenarios I'd use one of the Stream Matchers

expect(str.onChangeForGui, emitsInOrder([(e) => e != null]));

If you need to invoke code to cause the events to emit, you could use

final eventsFired = expectLater(str.onChangeForGui, emitsInOrder([(e) => e != null]));
// fire events
return eventsFired; // make the test work for this check 

Upvotes: 1

Related Questions