Test breaks when using Future.delayed

I have used a Future.delayed to show a FAB in 1 second using this code:

Future.delayed(const Duration(seconds: 1), () {
  setState(() {
    _showFab = true;
  });
});

Now the most basic smoke test has stopped working:

void main() {
  testWidgets('smoke test', (WidgetTester tester) async {
    await tester.pumpWidget(MyApp());

    expect(find.byType(MyHomePage), findsOneWidget);
  });
}

This is the error message:

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
A Timer is still pending even after the widget tree was disposed.
'package:flutter_test/src/binding.dart': Failed assertion: line 933 pos 7:
'_currentFakeAsync.nonPeriodicTimerCount == 0'    import 'dart:async';

Here is all the code used:

import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _showFab = false;

  @override
  Widget build(BuildContext context) {
    Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        _showFab = true;
      });
    });

    return Scaffold(
      floatingActionButton: AnimatedOpacity(
        opacity: _showFab ? 1.0 : 0.0,
        duration: Duration(milliseconds: 1400),
        child: FloatingActionButton(
          onPressed: null,
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

How can I change the unit test to make the test pass?

You need to give the tester enough time to process all the async calls you have scheduled, try change your smoke test to something like this:

void main() {
    testWidgets('smoke test', (WidgetTester tester) async {
    await tester.pumpWidget(MyApp());
    // Since you wait 1 second to start the animation and another 1.4 to complete it
    await tester.pump(Duration(seconds: 3));

    expect(find.byType(MyHomePage), findsOneWidget);
  });
}

You will also need to move the Future.delayed out of the build() method, because this is causing a cyclic behaviour, every time you call setState() the build() is called again, change your state like that:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _showFab = false;

  @override
  void initState() {
    Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        _showFab = true;
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: AnimatedOpacity(
        opacity: _showFab ? 1.0 : 0.0,
        duration: Duration(milliseconds: 1400),
        child: FloatingActionButton(
          onPressed: null,
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

Nuclear Safety, In each of the hot-leg break tests, the system was depressurized to 1.55 MPa. Therefore the results from the test with a delayed pump trip will not be discussed and to help in the planning and preparation for future Mod-2A experiments. Although you will not lose test time by taking an unscheduled restroom break between tests, it is recommended that you return from the break as quickly as possible (within 5–10 minutes) to avoid running over the scheduled appointment time. Test administrators are required to report test takers who take excessive or extended breaks.

The test framework runs with FakeAsync by default, that has some limitations and might cause the error you get.

You can explicitly run with async proper like:

void main() {
  testWidgets('smoke test', (WidgetTester tester) async {
    await tester.runAsync(() async {
      await tester.pumpWidget(MyApp());

      expect(find.byType(MyHomePage), findsOneWidget);
    });
  });
}

You might still need suggestions made in other answers.

The Shock and Vibration Bulletin, Impact Fuze Output Through Screen Box NOSE TIP POSITION FROM BREAK WIRE ( in ) Figure 8 . Effect of Velocity Errors on Impact Condition and Diagnostics Test Results The A delay of 90 us from the sled break wire contact to actual HE initiation signal output was ovserved This effect can be eliminated in the future . COVID-19 Test Results Delayed for Thousands Due to Broken Machine The backlog was discovered after questions were raised by NBC 7 Investigates.

You can wrap your Widget with TickerMode.

As you can see below:

void main() {
    testWidgets('smoke test', (WidgetTester tester) async {
    await tester.pumpWidget(TickerMode(child: MyApp(), enabled: false));
    await tester.pumpAndSettle();
    expect(find.byType(MyHomePage), findsOneWidget);
  });
}

Technology and the Future of European Employment, For this purpose we applied some tests of structural breaks. the 1980s or beginning of the 1990s, which is in line with our thesis of delayed deindustrialization. By using our site, Panthro. Software Architect at GFT Technologies AG. 7 Test breaks when using Future.delayed Jan 3 '19.

Try calling pumpAndSettle after you've pumped the widget. Like this:

void main() {
  testWidgets('smoke test', (WidgetTester tester) async {
    await tester.pumpWidget(MyApp());
    await tester.pumpAndSettle();

    expect(find.byType(MyHomePage), findsOneWidget);
  });
}

From the docs

This essentially waits for all animations to have completed.

Test breaks when using Future.delayed, Test breaks when using Future.delayed. Multi tool use. 1. Fade in FAB. I have used a Future.delayed to show a FAB in 1 second using this code  After making a number of changes to enhance the safety of those taking the test, as well as the staff working in the centers NCLEX test delivery at U.S.-and-Canada based Pearson VUE test centers, resumed on March 25th at a limited number of test centers in major metropolitan areas across the United States and Canada.

I tried using pump and pumpAndSettle but it didn't work. But add Duration in pumpAndSettle (not work for pump) makes it work again

await tester.pumpAndSettle(Duration(seconds: 1));

Factory, Perhaps you lack the time. tunity to exchange with other managers, by letter, Here is an opporKeeping cool in summer is accomplished in this testing room of the The break is repaired but nothing is done toward preventing future delays of  Planning ahead, staying hydrated and nourished, moving regularly, and setting goals with study break rewards will all help make studying easier and more enjoyable for your child. If your child needs help developing better study habits, Oxford Learning’s Study Skills Program can teach them the skills they need, including note-taking, creating

Congressional Record: Proceedings and Debates of the Congress, There is rarely any delay in obtaining a grand jury subpoena. I have asked the DOJ to take steps necessary to minimize future delays. As with roving wiretap authority, I believe section 215 has adequate It is kind of like those “in case of emergency, break glass” boxes that cover certain fire alarms and equipment. ACT may visit test centers to conduct additional test security measures on test day, such as collecting images of examinees during check-in and/or other security activities. After tests have been scored, the student’s photo will be printed on the score report that is automatically sent to the high school attended by the student.

'It's Just Everywhere Already': How Delays in Testing Set Back the , In fact, officials would later discover through testing, the virus had The continued delays have made it impossible for officials to get a true the study's laboratories to test cases and report the results only in future samples. The official practice tests from the maker of the test gives you the experience of taking the real, computer-delivered GRE General Test and more! Send Only Your Best Scores Approach test day with more confidence, knowing you can send the scores that show your personal best — only with the ScoreSelect ® option.

Transactions of the American Institute of Electrical Engineers, If you delay the opening up of the breaker, it is possible that some of the Now as to the influence of parallel feeders: These tests in Baltimore were all We are waiting with interest the results of breaking a short circuit of We trust that in the future other operators will take advantage of the results of these experiments. Sometimes you may want to send data in a stream. A stream consists of data sequence. Data can be pushed to a stream, while one or more listeners subscribe to the stream and get aware every time a new data added to the stream.

Comments
  • Thanks for the answer, though I'm still getting the same error with this smoke test. Even with await tester.pump(Duration(seconds: 2)); it still has the same error message.
  • You're waiting 1 second to start the animation that takes 14000ms, so it is 2400ms.
  • Thanks for the update, that still leads to the same strange error. I tried await tester.pump(Duration(seconds: 4)) just to be safe as well as await tester.pump(Duration(seconds: 3)) but still get the same error.
  • ohh I see now, you're adding the fab on your 'onBuild' method, that is causing a cyclic behaviour, move the call to init state.
  • Thanks, the onBuild was the issue as well
  • This answer also works when combined with the answer from @Panthro . Thanks
  • Yeah, normally you shouldn't need that. I run into a situation with rxdart where tests only worked with test.runAsync.
  • This did not work for me for the same error A Timer is still pending even after the widget tree was disposed.
  • Just tried that, I still have the same error message
  • oh ok, you might have to pass in a duration to your pumpWidget method call. await tester.pumpWidget(MyApp(), Duration(seconds: 1));
  • This also didn't work. Thanks for the suggestion though :)