Test side effects orchestration without pain
This piece of code is an assertion, an error will be thrown if something goes wrong:
- wrong io function
- wrong io arguments
- too much io ran
- not enough io ran
npm install --save handle-io
io is just a wrapper for functions and arguments. In some way, it transforms impure functions into pure functions.
Conceptually, an io function could just be defined in this way:
const log = consolelog args;
handle-io, it isn't.
Create IO functions
You can use
io to create one:
const io = ;const log = ;
Run IO functions
Running log with arguments:
; // print Hello World
Running log without arguments:
Keep in mind: pieces of code using
.run() cannot be tested properly.
The idea of this library is to apply an IO function inside a structure called handler.
A handler is a wrapped pure generator which just apply some IO function and/or handler.
const io handler = ;const log = ;const logTwice =;
Writing tests for handlers
Writing tests for handlers is very simple (please see the first example above).
What about testing a handler which applies an IO function and returns values ?
There is a very simple way:
- using the second argument of the .matchIo() method to mock returned values
- using .shouldReturn() to assert on the final value
const io handler = ;const getEnv = ;const addValues =;;
Same as for IO functions, there is a .run() method:
; // => 42// oraddValue;
Likewise, don't use handlers' .run() everywhere in your codebase.
handlers are combinable together: you can yield a handler.
handle-io supports promises and allows you to create asynchronous IO.
const io handler testHandler = ;// async ioconst sleep = ;// create an async combinationconst sleepSecond =;// test this combination synchronously;
Please note that
sleepSecond(n) will expose .run() methods that return a promise.
Dealing with errors
The simplest way to handle errors with
handle-io is to use try/catch blocks.
As you can see in the example below, you can try/catch any errors:
- inside a handler:
- thrown error
- inside an io function:
- thrown error
- unhandled promise rejection
const io handler = ;const handler1 =;// Synchronous IOconst io1 = ;// Asynchronous IOconst io2 = ;// handler2 is safe, it can't throw because it handles errorsconst handler2 =;
A functional helper exits to avoid try/catchs block, it allows to easily ignore errors and/or results.
Under the hood,
catchError uses a try/catch block and works similarly.
const io handler catchError = ;const ioError = ;const myHandler =;
How to test errors
By default, no mocked IO throws any error.
It's possible to simulate throws with
testHandler using the
simulateThrow test utility.
Writing tests for myHandler means two cases need to be handled:
testHandler can be created using
;const createCustomTestHandler =
There is a way to use
handler as redux middleware.
Please take a look to redux-fun Handlers.