Have you ever tried to test widgets that has Images fetched from the internet and got this error bellow?
If you answere yes you are on the right place! I’ll show you how easy is to setup your tests to avoid this kind of error.
First things first, let’s understand why Flutter is shouting at you. Every widget test in Flutter is pre configured to return a 400 code response to every HTTP request. That’s kind of what we expect for a controlled test, but with that comes a problem: how do we test for example a widget that loads an image from the network?
Flutter has no way “by itself” to handle this problem, you could always create your own MockHttp client and configure a default response for every network call, but that’s kind of a pain. So let’s get to a example and then i’ll give a simple solution for this. It’s a promisse.
Let’s pretend we have a simple Widget MyApp that only display a `Image.network` on a page. The test for that widget would be something like this:
If you run this test you will see the exact error i mentioned early.
So to fix this error a guy created a great package called `image_test_utils`. By magic and with few adjusts you widget tests with images will turn green :)
So import this package on the dev_dependencies of your pubspec.yaml file.
And the only adjust you have to do on your test is wrap your hole test on a provideMockedNetworkImages closure. That will make all your request to images return a mocked response with success.
So, doing this your test will be something like this:
And when running the test you will see the green test. Voilá!
So guys, that’s all for today, i hope you enjoy today’s tip. Stay tunned for more and Happy Coding!