Open Source Tooling and Automation Part 2: Unit Testing

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:

Screenshot from 2017-03-30 17-54-11.png

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!

Screenshot from 2017-03-30 17-58-24

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 seneca module 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:

1.png

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:

2.png

Now it’s the time to run out test. We can run it from the command-line.

3.png

And even though my first test failed, it’s okay. Let’s fix the code.

4.png

Now, let’s try to run our test again:

7

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s