What is unit testing?

Unit tests is every test that was built upon input or output declarations of a system(control data, usage procedures, and operating procedures). It is smaller testable part of your code.

What is the matter?

The importance of unit testing is to ensure with great granularity that all inputs and outputs of your code are working as you intended. This gives you the confidence that these isolated little pieces of your code will not break during use. To ensure complete security, it is important to write integration tests, which are responsible for testing the functioning of all your code together.

Writing tests for Mobx.

MobX is based on stores, actions and reactions using Transparent Functional Reactive Programming (TFRP) as it is functional, all actions are functions and their data are observable and reactive values. So testing your stores is extremely simple.

Let’s start with a counter.

Yes, that old same counter.

We will test if increment is occurring as we intended.

First, declare the test.

test(

‘When increment counter at 0 ‘

‘should return 1’, () { });

After that, we will declare the Counter store.

final counter = Counter();

We expect that the counter starts at 0.

For that, use the “expect” function, that receives a variable to be tested and the value that you expect as parameters.

expect(counter.value, 0);

Now, perform the increment and verify if the value was incremented.

expect(counter.value, 1);

To run your tests, run in console:

flutter test

or use IDE’s run all tests option.

Success!

Let’s to an complexer example, but not too much complex.

Testing a market cart.

The market cart is compose of a class that will represent the item and a store that will have a items list with add and remove functions.

Let’s test an item addition.

Declare the cart and the item that will be added, after that, perform addition function and expect that our list length will be increased to 1 and that contains our item.

test(

‘When add a item’

‘should contains that item, () {

final cart = Cart();

final item = CartItem(‘test’); cart.addItem(item); expect(todoList.items.length, 1); expect(todoList.items.contains(item), true);

});

Now, test the removal.

At the same way that we did with addition above, we will do with removal, expect that list lenght will be 0 and that not contains our item anymore.

test(

‘When remove a item’

‘should not contains that item, () {

final cart = Cart();

final item = CartItem(‘teste’); cart.addItem(item);

expect(cart.items.length, 1);

expect(cart.items.contains(item), true); cart.removeItem(item);

expect(cart.items.length, 0);

expect(cart.items.contains(item), false);

});

All cart tests:

Run the tests.

Now you are prepared to adventure the tests world using MobX.

Important advice:

It’s recommended that you use TDD that is tests driven development.