Codementor Events

Plug and play tests for ES6

Published Jul 03, 2018
Plug and play tests for ES6

This post follow my previous post on modular library building, but you don't have to read it first.

If you are here, I can bet you're aware of the importance of automated tests.

I wanted to find the most straightforward and easy way to test a browser modular library, so here's my findings.

Test suits

First of all, you need a test suit. There's plenty out there ! Like, a lot !!
Let's review a few and my opinion on each on of them.

Mocha - the flexible

Mocha is the most popular and built for browsers, but has two downsides in my opinion :

  • No assertion library built-in
  • Wordy compare to others

AVA - the rising-star

To be honest, I like AVA. It has a nice syntax, run tests blazing fast. The only pitfall is that it only support node and need an extra step (and configuration) to work with browser JS.

Jest - the handy

The best solution I found for our needs. Clear syntax, easy to set-up, fast, clean output ...
The cherry on top is that there's this webpack-jest package that set everything up for you.

Use Jest

This paragraph's gonna be short.

First, add some dev-dependencies.

npm install --save-dev jest jest-webpack

Then, add a "test" script into the package.json file.

"name": "myAwesomePackage",
"scripts": {
    "test": "jest-webpack"
}

Finally, run the "test" script with npm test.

That's it !

Write tests

By default, jest grab all file ending with .test.js, .spec.js or any files under a __tests__ directory as you prefer.

I'm not going to describe the whole deal, but the jest is pretty easy to grasp. Let me show you a meaningful example.

import Unicorn from "./myAwesomePackage.js";
import somethingElse from "AnotherPackage";

// Wrap this test suit
describe("Unicorn", () => {

    // Start every tests with a clean state
    let sparkle;
    beforeAll(() => {
        sparkle = new Unicorn("Sparkle");
    });

    // Some test
    test("instantiate", () => {
        // Simple assertion
        expect(sparkle instanceof Unicorn).toBe(true);
        expect(sparkle.name).toBe("Sparkle");
    });

    // More test
    test("shine", => {
        // String assertion
        expect(sparkle.shine()).toMatch(/🦄/);
        // Every assertion can be reverse using a "not"
        expect(sparkle.shine()).not.toMatch(/💩/);
    });

    // ...
});

Conclusion

You should now be able to test your ES6 code with very little set-up. 👍

Now, go and try to cover your code-base. But remember, smarter tests are better than a lot tests.

If you want to check a live example, I'm using the very same technique for my project of drawing library.

Discover and read more posts from Guillaume Martigny
get started
post commentsBe the first to share your opinion
Show more replies