Introduction

In this article, we will look at what are the different hooks available in Mocha Test Framework.

Before deep diving into hooks let us look at what is mocha

To install mocha use the below command,

  1. Describe blocks defines the Test Suite
  2. it block defines a Test case.
 describe('test suite name', function () {
    it('test case name', async ()=> {
      //test code to implemented
    });
  });
 

Hooks

Hooks are the preconditions and the postconditions that runs before and after your tests.

Below are the inbuilt BDD hooks available in mocha

Behavior Driven Development is a software development approach that allows the tester/business analyst to create test cases in simple text language (English).

describe('hooks', function() {
    before(function() {
        console.log('inside before hook')
    });
    after(function() {
        console.log('inside after hook')
    });
    beforeEach(function() {
        console.log('inside beforeeach hook')
    });
    afterEach(function() {
        console.log('inside aftereach hook')
    });
    // test cases
    it('testcase', function() {
        console.log('inside test block')
    });
});

Output after execution will be,

Note
Depending upon the no of test cases in your suite, the beforeach and aftereach block runs will run that many times

Ex: if there are two test cases then the output will be

TDD Hooks

TDD stands for Test Driven Development.

Test Driven Development (TDD) is a software development approach in which test cases are developed to specify and validate what the code will do.

Test Cases for each functionality are created and tested first and if the test fails then the new code is written in order to pass the test.

The below are available hooks for TDD in mocha,

In order to use this tdd hooks in mocha, we need to import the hooks from mocha modules

const {suite,test,setup,teardown,suiteSetup,suiteTeardown}=require('mocha')

Usage

import {suite,test,setup,teardown,suiteSetup,suiteTeardown} from 'mocha'
suite('TDD hooks', () => {
    suiteSetup(() => {
        console.log('one suitesetup')
    });
    suiteTeardown(() => {
        console.log('one suiteteardown')
    });
    setup(() => {
        console.log('one setup')
    });
    teardown(() => {
        console.log('one teardown')
    });
    // test cases
    test('testcases', () => {
        console.log('one test')
    });
});

Output after execution will be,

Note
Depending upon the number of test cases in your suite, the setup and teardown block runs will run that many times

Ex

If there are two test cases then the output will be,

Summary

Hope this article was interesting in learning the different hooks available in Mocha Test Automation Framework. Hope this will be helpful while writing Test Automation scripts.