Unit Testing Frameworks
There are a lot of Unit Testing Frameworks, David Humphrey provided some suggestions for us:
I want to try using Jest.
Writing our first Test
First, I am going to install Jest. You can find the instructions here. Or just follow with me 🙂
In order to install, we need to run the following command:
npm install –save-dev jest
And it going to look something like that:
Basically, by running this command we installing Jest to our node_modules directory and also save it as a DevDependency in our package.json file. So let’s see how our package.json looks now!
As you can see now we have DevDependencies, with Jest added on the last line. Looks great so far!
The next step is writing the test. I really like what my Professor wrote about unit testing in the instructions and I want to have it in my blog to share this information with people who read the blog and for myself to remember.
“Next, I need to add a test. What should we test? Learning what to test, and how to write useful and complete tests is an art. It takes time, and practice will help you.
To begin, let’s write a single test for our
senecamodule and the
isValidEmail()function. A unit test should test one thing, and one thing only. Instead of trying to write a single test that will test everything at all once, we’ll write many small tests, each of which tests a single aspect of the code.” (https://github.com/humphd/Seneca2017LearningLab/blob/master/README-part2.md)
Now, when we know this useful information, we can move on to writing our first unit test. I am extremely excited!
Now I am going to create a new file: seneca.test.js. Which looks like this:
Running a test
Just something to keep in mind:
It’s often a good idea to write tests before you write your code. This is called Test Driven Development (TDD), and helps to make sure that your code evolves in ways that are expected, documented, and safe. It’s not always necessary, appropriate, or possible to do this, but it’s something to keep in mind. (https://github.com/humphd/Seneca2017LearningLab/blob/master/README-part2.md)
So let’s see how my implemented function is looks like:
Now it’s the time to run out test. We can run it from the command-line.
And even though my first test failed, it’s okay. Let’s fix the code.
Now, let’s try to run our test again: