CodeWithMMAK
Test AutomationIntermediate

Test Automation using Mocha, Chai, and TypeScript

A comprehensive guide to setting up a test automation framework using Mocha, Chai, and TypeScript for modern JavaScript applications.

CodeWithMMAK
December 26, 2018
3 min

Introduction

🎯 Quick Answer

Mocha, Chai, and TypeScript form a robust and highly flexible testing stack for Node.js applications. Mocha provides the test runner framework, Chai offers expressive BDD/TDD assertions, and TypeScript adds static typing to ensure your test code is maintainable and error-free. This combination is particularly effective for enterprise-level projects where code quality and clear documentation are paramount.

Today we will be setting up a test framework using one of the famous JavaScript tools named Mocha and the Chai Assertion library with TypeScript as the programming language.

📖 Key Definitions

Mocha

A feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.

Chai

A BDD / TDD assertion library for node and the browser that can be paired with any javascript testing framework.

ts-node

A TypeScript execution engine and REPL for Node.js, allowing you to run TypeScript files directly without manual compilation.

Assertion

A boolean expression that checks if a condition is true, used to verify the expected behavior of code.

What is 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.

What is Chai?

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

🚀 Step-by-Step Implementation

1

Prerequisites

Ensure you have Node.js and Visual Studio Code installed.

2

Initialize Project

Create a folder named mocha-chai-typescript and run npm init to create your package.json.

3

Install Core Dependencies

Run npm install chai mocha ts-node typescript --save to install the testing framework and TypeScript support.

4

Install Type Definitions

Install necessary types and dev dependencies: npm install @types/chai @types/mocha rimraf tslint --save-dev.

5

Create Page Objects

Create a page-objects folder and define your application logic or helper functions in .ts files.

6

Write and Run Tests

Create a test-suite folder, write your .spec.ts files using Mocha's describe and Chai's expect, and execute them using npm test.

Building the Framework

Let's go through the step-by-step process of creating an automation framework using Mocha, Chai, and TypeScript.

  1. Install Node.JS
  2. Install Visual Studio Code

Setup Steps

  1. Create a folder named mocha-chai-typescript.
  2. Initialize your project and install dependencies:
Code Snippet
npm install chai mocha ts-node typescript --save
  1. Install dev dependencies:
Code Snippet
npm install @angular/compiler @angular/core @types/chai @types/mocha codelyzer rimraf rxjs tslint typings zone.js --save-dev

Creating Your First Test

Create a folder named page-objects. Inside it, create first-test.po.ts:

Code Snippet
export function hello() {
    return 'Hello world!';
}

export default hello;

Now create a folder named test-suite. Inside it, create first-test.spec.ts:

Code Snippet
import { hello } from '../page-objects/first-test.po';
import { expect } from 'chai';
import 'mocha';

describe('First Hello World Test: ', () => {
    it('Should return Hello World', () => {
        const result = hello();
        expect(result).to.equal('Hello world!');
    });
})

⚠️ Common Errors & Pitfalls

  • TypeScript Compilation Errors

    Ensure your tsconfig.json is correctly configured. If ts-node fails, check if your imports use the correct relative paths.

  • Missing Type Definitions

    If you see errors like "Cannot find name 'describe'", ensure you have installed @types/mocha and @types/chai.

  • Async Timeout

    Mocha has a default timeout of 2000ms. For long-running tests, use this.timeout(5000) inside the it block or configure it in the command line.

Best Practices

  • Use Page Object Model (POM) to separate test logic from application interactions.
  • Leverage Chai's BDD style (expect) for more readable and descriptive assertions.
  • Organize tests into logical suites using nested describe blocks.
  • Use before and after hooks for setup and teardown tasks to keep tests clean.

Frequently Asked Questions

Can I use Mocha for frontend testing?

Yes, Mocha can run in the browser or be used with tools like Karma or Selenium for frontend automation.

What is the difference between expect, should, and assert in Chai?

expect and should are BDD styles, while assert is TDD style. expect is generally preferred as it doesn't modify Object.prototype.

How do I generate HTML reports?

Use reporters like mochawesome to generate beautiful HTML reports of your test execution.

Running the Test

To run your tests, use the following command:

Code Snippet
npm test

You can see the results in the console. Also, you will get an HTML report generated in the test-results folder using mochawesome.

Code Repository

The sample framework is hosted on GitHub: mocha-chai-typescript

Have a suggestion or found a bug? Fork this project to help make this even better.

Conclusion

Setting up Mocha and Chai with TypeScript provides a powerful foundation for any testing project. The combination of Mocha's flexibility, Chai's expressiveness, and TypeScript's safety ensures that your automation suite remains maintainable and reliable as your application grows.

📝 Summary & Key Takeaways

This guide provided a comprehensive walkthrough for setting up a test automation framework using Mocha, Chai, and TypeScript. We covered the core definitions, detailed a step-by-step installation process, and provided a practical "Hello World" test example. By emphasizing best practices like the Page Object Model and BDD-style assertions, and addressing common pitfalls like missing type definitions, this tutorial empowers developers to build high-quality, typed testing suites for modern JavaScript/TypeScript applications.

Share it with your network and help others learn too!

Follow me on social media for more developer tips, tricks, and tutorials. Let's connect and build something great together!