Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of jest snapshot testing in Flutter?

Tags:

flutter

dart

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?

like image 830
Rémi Rousselet Avatar asked Nov 15 '18 13:11

Rémi Rousselet


People also ask

What is snapshot testing in Jest?

Snapshot tests are useful when you want to make sure your UI does not change unexpectedly. A typical snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test.

Is snapshot testing is supported in Jest?

Snapshot Testing with Jest​ `; The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses pretty-format to make snapshots human-readable during code review.

How do you write snapshot Jest?

When writing snapshot tests for a React component, you first need to have code in a working state. Then, generate a snapshot of its expected output given certain data. The snapshot tests are committed alongside the component. Jest, a testing framework, will compare the snapshot to the rendered output for the test.


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
like image 87
Rémi Rousselet Avatar answered Sep 20 '22 15:09

Rémi Rousselet