窗口小部件测试使用WidgetsBinding.instance.addPostFrameCallback()的窗口小部件

时间:2019-08-22 15:26:28

标签: flutter flutter-test

我正尝试对一个使用WidgetsBinding.instance.addPostFrameCallback()来显示窗口小部件生命周期开始的对话框的窗口小部件进行一次窗口小部件测试。

窗口小部件工作正常,但是我无法弄清楚如何进行窗口小部件测试,因为测试的第一个Expect()在触发此后框架之前就已执行。

是否要“告诉”测试以等待所有发帖帧被分派?

PD:tester.pump(),tester.pumpAndSettle()等无法正常运行。

3 个答案:

答案 0 :(得分:1)

但是您知道什么...突然弹出:

    tester.binding.scheduleWarmUpFrame();

运行:-)

从这里拍摄:https://chromium.googlesource.com/external/github.com/flutter/flutter/+/v0.9.2/packages/flutter/test/widgets/binding_test.dart

答案 1 :(得分:1)

这对我有用:

// press button
await tester.tap(find.text("Save"));
// await the flushbar or snackbar to appear
await tester.pumpAndSettle(const Duration(seconds: 1));
// find by text or key
expect(find.text("Error saving note"), findsOneWidget);
// this prevents this error:
// A Timer is still pending even after the widget tree was disposed.
// the flushbar in my code is displayed for 5 seconds. So we wait for it to 
// go away.
await tester.pumpAndSettle(const Duration(seconds: 5));

我不知道这是否是正确的方法。但这有效。 祝你好运!

答案 2 :(得分:0)

要在 Flutter 测试环境中安排框架(并强制调用 postFrameCallback),您需要在 tester.binding.scheduleFrame() 之前调用 tester.pump()

或者,如果您不关心正在重建的整个小部件树,您可以调用 tester.pumpWidget(widget) 而不是 tester.pump()

示例测试:

testWidgets('testing frames', (tester) async {
  final w = Container();
  int framesCount = 0;

  tester.binding.addPersistentFrameCallback((timeStamp) {
    framesCount++;
  });

  await tester.pumpWidget(w);
  expect(framesCount, equals(1));

  // pumpWidget calls [scheduleFrame]
  await tester.pumpWidget(w);
  expect(framesCount, equals(2));

  await tester.pump();
  // no frame was scheduled, so framesCount is still 2
  expect(framesCount, equals(2));

  tester.binding.scheduleFrame(); // --
  await tester.pump();            //   |
  expect(framesCount, equals(3)); // <-

  // pumpWidget calls [scheduleFrame]
  await tester.pumpWidget(w);
  expect(framesCount, equals(4));
});