What is an app without tests? Today I will describe how I configured tests, what do I use for testing and how do I write simple unit tests.
Actually the code was ready at the beginning of the week, but somehow I couldn’t get to describe the next step. To not let it be a week without posting, I’m catching up on Sunday night.
First things first
What we get right away thanks to
create-react-project, let’s look to the file
The command to run tests is
react-scripts test --env=jsdom. Well, we look further what is the mysterious
react-scripts (of course you will find it in the directory
node_modules or on github):
So it runs tests using Jest. Jest doesn’t require any particular configuration, therefore there is nothing more interesting to see in this file. Test files are detected based on the name. They should be named
Facebook also suggests that Airbnb released Enzyme testing tool. It’s worth using it. Thanks to it testing of React components is easier. I installed the module by running the command
npm install enzyme --save-dev. I installed also
jest-enzyme. What was needed was one more line in configuration:
The first component that I want to test is
App, which is a kind of layout for the whole application. For now it contains the header, navigation and displays the content of individual pages. App is the parent component, to which are added the individual components which are subpages. As a reminder, the definition of routing below:
The first main test for each component may be to check whether it renders.
So I’m trying to render a component using
ReactDOM.render and if no errors the test passes.
Now comes into play Enzyme. I write a test that checks whether the component contains a header with the expected text.
Another test is to check whether the navigation is present and children render in the right place:
- nodejs version 6,
- notifications in Slack instead of email.
That’s it for the beginning of the testing. The real fun starts with a real interface in the Material UI.
Link to the project repository https://github.com/mkutyba/FormularzeKonsumenckie