Setting up a testing environment
From the time I started coding, I heard mention of the phrase Test Driven Development, without really knowing what that meant but every mention was of its importance and its benefits on robust applications…
Still, that all meant very little. My first real experience with coding was solving failing tests! It was a nice way to see how the components all fit together. I loved to debug and turn all the failed tests to passing green. It was the catalyst of my enjoyment with coding.
Time to quickly discuss and go through the motions of setting up a testing environment! Personally I like to use Jest. I find it to be fairly simple, and its the only one I’ve actually tried to understand.
First, in your project go ahead and add the dev dependencies indicated by the “-D” flag: jest and babel-jest…
And because I want to write es6 JavaScript in my test files as well, I always include babel-jest. Just to reiterate, babel-jest lets us write e6 JavaScript for our test files!
Next its time now that we add a file to our project, lets call it jest.config.js…
Now to fill out the file…
It is a module so we will be using module.exports and in this we are going to specify our testEnvironment: ‘node’, the reason for this step is that jest is used to test front-end applications as well, so specifying ‘node’ removes the ‘virtual DOM’
And since we don’t want this to run through all the node modules…
We use coverPathIgnorePatterns: [‘node_modules/’]. Now its time to add a test folder and then to write a sample test to ensure that we have setup Jest and connected it properly. So for now go ahead and create a new folder called “__tests__” important to use the double underscore on either side of tests, which is the default that Jest is going to look for and run. And in that folder create a new file, and we will call this test.spec.js…
Finally, lets go ahead and write our first sample test… Jest uses describe blocks for its tests. So we start with describe ‘test’ because this is just a test, then an anonymous callback function and we are going to ‘test’ whether or not it works with another callback function where our expect statement is written. Again, this is just to test that we are actually connected so we are just looking for true toBe true…
So now we can run our test by typing yarn jest in our terminal…
And if it is setup up correctly, we should see green tests…
And there it is, you should be all setup to start implementing Test Driven Development into your applications!