Testing components with Mycoriza hooks.
Unit testing is a crucial part of software development. Being a state based library, Mycoriza provides the necessary tools to write the unit tests for the components using the mycoriza generated hooks.
Mycoriza is backed by redux and redux provides a comprehensive guide on writing testis. It is recommended to refer the material.
Setting up the tests.
Mycoriza provides a testStore
which accepts the generated reducer
, middlewares
and the stubs
which are related to the CUD.
Warning
Make sure not to include the middlewares which are bound to issue remote calls as it affects the unit testing.
Tip
The generated stubs are meant to stub the redux-axios-middleware with more control.
The testStore
can be used alongside the react-redux Provider
to create the tests, and the stubs
should be initialized with the factory generated.
import {render} from '@testing-library/react';
import {Provider} from "react-redux";
import {testStore} from "mycoriza-runtime";
//Import stubForMyHook
...
let myHookStub = stubForMyHook()
render(<Provider store={testStore({
rootReducer: rootReducer,
stubs: [stubForMyHook]
})}><MyComponent/></Provider>);
//Use stub within the test
...
The created stub can be used within the test.
Autogenerated stubs for hooks.
Mycoriza generates the stubs alongside the hooks in <hook-name>.test.ts
file.
These stubs provide following functionalities.
get current state.
The stub contains the method currentState
to get the current network state in the store.
currentState
method accepts an entityKey
, which can be used to identify the unique values.
The currentState
is a NetworkState
and utility functions can be used with the states.
import {isSuccess} from "mycoriza-runtime";
...
expect(isSuccess(myHookStub.currentState())).toBeTruthy()
change states
The stub provides four methods to change the state. Each method accepts the entityKey
with usual meaning.
reset
Reset function will set the state to init state
myHookStub.reset()
toPendingState
toPendingState
function changes the state to pending state.
myHookStub.toPendingState()
toSuccessState
toSuccessState
function changes the state to success state. This function accepts a value
of the type T
of hook, and stores as the current value.
myHookStub.toSuccessState("Foo")
toErrorState
toErrorState
function changes the state to error state. this function accepts a value
as an error and stores as the current error.
myHookStub.toErrorState("Some Error")
Conclusion
The Mycoriza test environment is designed to be able to integrate with any testing environment
which redux supports, like @react-testing
or enzime
. Altogether, writing unit tests to observe
the behaviors of the components is a best practice and encouraged by Mycoriza. For any enhancement
or issue please report an issue in github repository.