Testing Node Application: Tutorial 1 (Basic Testing with Mocha)

Words
307
Reading
2 min
Listen
Play
9y

Getting Started with Mocha

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting while mapping uncaught exceptions to the correct test cases.

Mocha_retina.jpg

This tutorial will walk you through its installation and configuration, as well as demonstrate its usage by testing two basic functions

If you have setup Test cases for other languages, then you know how hard it can be to get started. You have to setup actual test infrastructure and then you have to write your individual test cases. This is why most people don’t test their application because it’s a burden to test Applications.

Lets Get Started.

A. Setting Up Testing Suite for Node Application

  1. Navigate to the project directory
  2. Enter this command: npm init
  3. Create the js file. we created a utils.js in utils directory.
  4. we wrote this functions in the utils.js file.
let add = (a, b) => a + b;

let square = (x) => x * x;

module.exports = {add, square} 

Screenshot below
Screen Shot 2018-01-02 at 6.25.58 AM.png

B. Installing and Configuring Mochas. (you can visit: mochasjs.org for more information)

  1. Install mocha:
    $ npm I mocha --save-dev

  2. Next, we create a file called utils.test.js

  3. Import the utils file containing the functions we want to test.
    const utils = require('./utils')

  4. (it) lets us define a new test case and it takes 2 arguments.

  • What should be done
  • Function.
it('should add two numbers', () => {
    let res = utils.add(33,11);
    if (res !== 44){
        throw new Error('Expected 44, but got' + res) }
});  

it('should square two numbers', () => {
    let res = utils.square(3);
    if (res !== 9){
        throw new Error(`Expected 9, but got ${res}`)
}})

Screenshot
Screen Shot 2018-01-02 at 6.26.10 AM.png

  • Change the value of the test in package.json file to mocha / your test file.
"test": "mocha **/*.test.js" 
  • Run $ npm test. We should see success if the test passed. Screen Shot 2017-12-31 at 6.15.59 PM.png

If we mess up one of our function, we get a failure. see below.
Screen Shot 2017-12-31 at 6.16.31 PM.png

Conclusion

Mocha is a nice and easy DSL that makes writing tests very easy and straightforward.

With this simple tutorial, you can go ahead and start testing your functions.

The next tutorial, we would be exploring more mocha methods & we would be using assertion library.

See codes here: https://github.com/Rhotimee/node-tests

Screen Shot 2018-01-02 at 6.25.31 AM.png



Posted on Utopian.io - Rewarding Open Source Contributors

Testing Node Application: Tutorial 1 (Basic Testing with Mocha) | Ecency