Widget testing passed in functions

Reme Le Hane
Wyzetalk Tech
Published in
2 min readJul 10, 2020

--

In this post, we going to go through how, at least in my opinion, one would go about testing that a function is called within a widget when that function is one of the Widgets arguments.

Take the following overly simplified example…

class SampleWidget extends StatelessWidget {
final Function(String fileId) onDelete;
final String fileId;

const SampleWidget({
@required this.onDelete,
@required this.fileId,
foundation.Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
throw FlatButton(
onPressed: () => onDelete(fileId),
child: const Text('Delete'),
);
}
}

As you can see we have a simple “reusable” widget that takes a fileId and a onDelete function.

Testing this in the implementing widget is quite simple as you would simply verify the resulting function is called.

However, if you wished to test this widget in isolation, there are a few more steps required.

In our current project, we added a very simple helper class:

class TestCallbackFunctions {
void onFileDelete(String fileId) => null;
}

This class will then hold simply “mock” functions that we can pass into reusable widgets to test it completely.

I hope you found this useful, and if you have any questions, comments, or improvements, feel free to drop me a comment.

Thanks for reading.

About Wyzetalk
Founded in South Africa and headquartered in The Netherlands, Wyzetalk is a leading global employee experience company that offers a mobile-first digital solution connecting large organisations with their dispersed, frontline workforce to improve communication, unleash innovation, and boost business performance. Since launching in 2012, the company has grown in revenue by more than 100% per annum. With a presence in 18 countries across five continents, today there are 650 000 employees making use of the Wyzetalk platform through clients in the Mining, Retail, FMCG, Manufacturing, Energy, Automotive and Shipping sectors.

Website: https://www.wyzetalk.com/

--

--

Reme Le Hane
Wyzetalk Tech

Runner, Developer, Gamer. | Lead Frontend Engineer at Loop with 14 years Front-End Experience & ~4yrs Flutter. | React Flutter Javascript Dart