Simplifying jest stubs using jest-when
Published by Manuel Rivero on 29/09/2022
While test-driving the
UnusualSpendingDetector class we found that writing stubs using plain jest can be a bit hard. The reason is that jest does not match mocked function arguments, so to create stubbed responses for particular values of the arguments we are forced to introduce logic in the tests.
Have a look at a fragment of the tests we wrote for
paymentsRepositoryWillReturn helper function, we extracted it to remove duplication in the tests. In this function we had to add explicit checks to see whether the arguments of a call match some given values. It reads more or less ok, but we were not happy with the result because we were adding logic in test code (see all the test cases).
Creating these stubs can be greatly simplified using a library called jest-when which helps to write stubs for specifically matched mocked function arguments. Have a look at the same fragment of the tests we wrote for
UnusualSpendingDetector class now using jest-when:
Notice how the
paymentsRepositoryWillReturn helper function is not needed anymore, and how the fluent interface of jest-when feels nearly like canonical jest syntax.
We think that using jest-when is less error prone than having to add logic to write your own stubs with plain jest, and it’s as readable as or more than using only jest (see all the refactored test cases).
To improve readability we played a bit with a functional builder. This is the same fragment of the tests we wrote for
UnusualSpendingDetector class now using a functional builder over jest-when:
PaymentsRepositoryHelper is as follows:
In this last version we were just playing a bit with the code in order to find a way to configure the stubs both in terms of the domain and without free variables (have a look at all the test cases using this builder). In any case, we think that the previous version using jest-when was already good enough.
Probably you already knew jest-when, if not, give it a try. We think it can help you to write simpler stubs if you’re using jest.