DEV Community

Brandon Weygant
Brandon Weygant

Posted on • Updated on

Learning To Write Your Own Test Cases Part 3 - Using Mocha

Don't forget to checkout Part 1 & Part 2 as well.

Credits & Intro

Once again, credits first. This tutorial by Glad Chinda helped immensely in getting me off the ground with mocha setup & testing. One thing to take into consideration though is his sample test cases aren't as beginner-friendly on the solution side of things, and if you recall I set out with the intention of creating a beginner's curriculum for newbies to JavaScript. This is not a deal-breaker in any way for me, nor should it be for you be unless you too are specifically writing tests for novices as well. Glad's tutorial outside of his solution is extremely beginner-friendly and takes almost all of the headache/intimidation of setting up Mocha in your environment. Secondly, no good guide can ever give proper credits without mentioning the official docs, and the Mocha docs are extremely helpful as expected. And lastly, I opted to use Chai as my assertion library, and the Chai docs helped out quite a bit as well.

Why Mocha?

Well, the biggest reason to test in Mocha is how much support has gone into it over the years. Unlike Jest, which is fairly new, Mocha has quite a few more years under its belt and as such many more libraries and customizability features.

Why Not Mocha?

The biggest, and by far the most significant drawback to Mocha, is the fact it doesn't come ready and feature-rich right out the box. You have to install an assertion library yourself, which gives you freedom of choice to customize further but is ultimately an extra step. It also doesn't support writing your tests in ES6 without taking even more additional steps.

Getting Started

This is not a comprehensive guide, and you can always skip the GitHub portions if you don't wish to save anything and just want to practice. See Glad Chinda's guide from above for a more detailed explanation

Step-by-step guide

  1. Create new Github repo w/LICENSE
  2. Clone repo to your machine
  3. Create .gitignore
  4. Create README
  5. Run npm init to create package.json (specify test script as "mocha")
  6. Run npm install --global mocha for global install OR npm install --save-dev mocha if you prefer non-global install
  7. Run npm i --save-dev chai to do a dependency install of chai to your project (or choose a different assertion library)
  8. Create index.js (or alternate solution file location)
  9. Create a test folder w/ test file(s). An example would be myFunct.js or add.js
  10. Add the line var expect = require('chai').expect; in your test file(s) to enable chai or your tests will not work!
  11. Export your solution file by adding module.exports = {myFunct1, myFunct2, etc} to index.js or whatever you named your file.
  12. Finish connecting your solution file to your test suite by adding const {myFunct1, myFunct2} = require('../whateverYouNamedYourSolutionFile’); inside your test file(s).

Note: It's good practice to make separate test files for each function. For example requiring only {myFunct1} in one file and {myFunct2} in a different file can simplify not only your test writing, but can unclutter your code, and even make it more readable on the user end. I chose to clutter everything together in this project because that level of organization was not my priority in this project.

Also Note: const mocha = "Mocha/Chai" Don't add this line of code anywhere, just understand for simplicity's sake I am identifying Mocha and Chai as one from here on out.

Writing Basic Test Cases with Mocha

While the actual writing of test cases in Mocha does not differ all that much from how we wrote it in Jest, there are some significant differences. Below is the test we wrote in part 2 of this series using Jest:

describe('add', () => {
        test('add() is a function that returns the sum of 2 arguments', () => {
         expect(add(1, 2)).toBe(3)
    })
Enter fullscreen mode Exit fullscreen mode

That same test would be written in Mocha like this:

describe('add', function(){
        it('add() is a function that returns the sum of 2 arguments', function(){
         expect(add(1, 2)).to.equal(3)
    })
Enter fullscreen mode Exit fullscreen mode

Explaining The Differences

While you may notice our old friends describe() & expect() have stuck around to reprise their roles, there is still some unpacking to be done here.

First, notice the absence of arrow functions. Tests in Mocha do not support ES6 out of the box, you would have to add them through more installs.

Secondly, the test() function from Jest is now called the it() function. By all accounts, it functions the same way.

And lastly, the toBe() from Jest is replaced with the to.equal() in Mocha. This is just a micro-sample of the slight yet significant syntactical differences between the two, where Jest tends to combine words into one larger function and Mocha tends to have each individual word performing smaller tasks in the test suite.

But Enough of All That!

You've written your first test using Mocha! Give yourself a big-up if you haven't already! I mean, that was the goal, right? Mocha is absolutely LOADED with features and libraries that no other test framework can compare to yet, so diving too deep into the possible benefits is better done by people way more knowledgable about Mocha than me. Here are some the more general pro's & con's I've noticed.

Pro's

Highly customizable - It's worth repeating 1000x - Mocha has unrivaled support and libraries. Anything you could possibly want to do with your tests, Mocha has a resource or library you can add to do it.

More widely used - Individual projects aside, there is more (if only slight) value in learning Mocha if only because it is the most established and widely used test suite out there.

Not as difficult to install as you are lead to believe - Getting started with Mocha is not as huge a burden as some others will have you believe. 1-2 extra lines in the CLI and test code is really the only difference, and those 1-2 lines unlock a lot of power!

Con's

That's still 1-2 extra steps more than with other test suites - Yup, programmers are in fact lazy by nature, so this is still a heavy burden to bear.

No out of box support for ES6 - This is a personal bummer for me as the ES6 syntax is so much cleaner and appealing to look at. Also, easier to keep track of all your {}, (), ;, etc.

There is a trend forming here - Also a personal preference, the toBeTruthy style syntax Jest provides is easier than the equivalent to.be.ok Chai does. Add in toBeFalsey is to.not.be.ok and you can see how putting a dot after every word (as natural and colloquial as it sounds) rather than just typing in a function name can get tiring.

So Basically... You can sum up all of the above into one bigger con: the extra work lazy asses like me have to put into it. I'm too old to change. Don't judge me.

In Conclusion

I personally preferred my experience with Jest, but that can easily be attributed to not just my overall experience level writing tests, but also that the project that inspired me was simple in nature. There was little reason to research all of the add-ons and libraries Mocha provides because I myself was learning to write simple tests. But, it doesn't change that Mocha compared to Jest does feel a bit dated to me, if mostly because of the extra steps and no ES6 support out of box. So my personal recommendation is currently split:

If you are learning test-writing or working on smaller (even smaller work-related) projects, Jest will have you spending less time on your test suites and more time on your projects.

But, if you are running a larger project or need a highly customizable test suite, Mocha wins out for me (for now).

I hope you enjoyed my take on learning to write your own test cases as much as I enjoyed writing about them. Thank you for reading.
If you are interested in checking out what I have done on my sample testing project, check out the GitHub repo.

Top comments (0)