DEV Community

Cover image for Testing a easy method with Mocha and Javascript
Cristian Estarlich
Cristian Estarlich

Posted on

Testing a easy method with Mocha and Javascript

🔌 Installation

First init the repo and install mocha:
Image description

Now let's try if mocha works, creating a folder called test in the root of the project and inside this folder creating a file:
Image description

🎮 Playing with mocha

That file will contains an easy assert that checks if a variable contains the string that we expect:
Image description

Voilà, it works like a charm:
Image description

If we try to put a test that is wrong:
Image description

The test will fail:
Image description

🏆 The real example

We will create a file called strings.js that will contains only one function called stringMerge, super easy:

Image description

Special mention to Mintlify extension that writes all JSDocs for me 😃

and finally the test:

Image description

Some considerations here:

  • In the line 2 we're loading the file that contains our famous method.
  • We're implementing the triple A pattern (Arrange, Act, Assert) you can find more info searching on Google.
  • The magic happens in line 17 when we're checking the result of our method.

And the result:
Image description

That's it for today! I will try to create another easy post before Sunday with Jest.

Top comments (0)