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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With