Write a unit test for a Frint-React component
In this first article of a serie of 3 we are going to write a test for the root component of the counter-app in the kitchensink example available in the Frint repository on Github.
The sources can be found here: https://github.com/Travix-International/frint/tree/master/examples/kitchensink
I assume that everybody is already aware of what Frint is so let’s start coding.
First, clone the Frint repository. Go to the counter-app directory in examples → kitchensink. Run npm i
.
The root component can be found here: https://github.com/Travix-International/frint/blob/master/examples/kitchensink/app-counter/components/Root.js
In our case we will focus on what the component renders.
What do we want to test?
We want to check that our component is correctly rendering. For checking this let’s assert that it contains “<strong>Services:</strong>” and it calls getAppName
from the ‘Foo’ and ‘Bar’ providers.
What do we need for the test?
We have to mount the component to have access to its DOM, so we can verify if it contains the elements mentioned before.
To do this, we will use the framework mocha with enzyme.
Here is a basic setup for the “mocha.opts” file:
--colors
--compilers js:babel-register
--require frint-test-utils/register
--require ./test/config/bootstrap.js
--recursive
In the bootstrap file we define all the test utilities.
Now that we are done with the setup, let’s write the first test.
We need to mock the Frint application for mounting the root component :
In our mock, the first item of the providers list is the counter-app’s Root component. Foo and Bar are spies. We will use them for verifying that they have been called. The store defines the initial state of the component.
Writing the test
Now that the mock is created, let’s write the code to test the expected behaviour.
Frint-React function getMountableComponent
takes as argument the instance of the mock App we created. It returns a mountable React component that we can mount using Enzyme mount
function.
Now that our test is ready, run the following command:
npm test
You should see the test passing.
The sources for the article are available here: https://github.com/Travix-International/frint/tree/master/examples/kitchensink/app-counter
Don’t hesitate to leave a comment if you have any questions regarding the article.
Enjoy !