loading...

Widget testing passed in function

remejuan profile image Reme Le Hane Originally published at Medium on ・1 min read

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.


Posted on by:

remejuan profile

Reme Le Hane

@remejuan

Runner, Cyclist, Developer, Gamer.

Discussion

pic
Editor guide