DEV Community

Cover image for Plug and play tests for ES6
Guillaume Martigny
Guillaume Martigny

Posted on • Edited on

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
Enter fullscreen mode Exit fullscreen mode

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

"name": "myAwesomePackage",
"scripts": {
    "test": "jest-webpack"
}
Enter fullscreen mode Exit fullscreen mode

Finally, run the "test" script.

npm test
Enter fullscreen mode Exit fullscreen mode

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(/🦄/);
        expect(sparkle.shine()).not.toMatch(/đź’©/);
    });

    // ...
});
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)