What is the equivalent of jest snapshot testing in Flutter?

Viewed 1729

Using Jest, a testing library for JS, it is possible to have a "snapshot" as followed:

test('foo', () => {
    expect(42).toMatchSnapshot("my_snapshot");
})

Basically, on first run this saves the tested value into a file. And on later runs, it compares the passed value with what was into the file. So that if the passed value differ from the value inside that file, the test fail.

This is quite useful because it allows to create tests easily.

Is there any way to do this using the testing framework provided by Flutter?

1 Answers

It is possible for widgets only, using testWidgets:

testWidgets('golden', (tester) async {
  await tester.pumpWidget(Container(
    color: Colors.red,
  ));

  await expectLater(
      find.byType(Container), matchesGoldenFile("red_container.png"));
});

First, you have to pump the widget you want to test (here a red container).

Then you can use matchesGoldenFile combined with expectLater. This will take a screen capture of the widget and compare it to the previously saved capture.

On the first run or when you want to update your goldens, you'll have to pass a flag to flutter test:

flutter test --update-goldens
Related