Jun 12, 2020 / flutter
Automatically running flutter tests when a file changes

It's pretty easy to write unit tests for Flutter. The annoying thing is that there's no way to continuously run the tests each time you change a file. I find unit testing much better when tests run automatically as I code so I know when something is broken. I was hoping there would be a flutter test --watch but there isn't yet.

However, I worked out a hack that seems to work well.

brew install fswatch
fswatch -e ".*" -i "\\.dart$" . | xargs -n1 -I {} sh -c "echo $'\e[1;31m'{}$'\e[0m'; flutter test -j 2 ./test"

If you run this from the root of your application, you'll find that each time you tweak a .dart file, the tests all run again. There's probably a nice way to only run specific tests, but this will do me for now.

I'd also recommend you throw this in a file called watch_test.sh so all you need to do is type sh watch_test.sh. No need to remember the long command above.

If you find tests are too slow to watch continuously, consider fixing it. Tests should be fast.

  • Tests that hit the network are slow, you could always add a skip flag to slow tests and test them individually later. Or even better, mock them out.
  • Tests that hit the DB can be slow too, I'd recommend mocking that out too.

Enjoy

P.S - Credit to Warun K for inspiring this with his article here.


You may also like...