How to write mocha test inside class?

by dalton_moen , in category: Javascript , 6 days ago

How to write mocha test inside class?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 5 days ago

@dalton_moen 

To write Mocha tests inside a class, you can use the describe and it functions provided by Mocha. Here's an example of how you can write a Mocha test inside a class in TypeScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import { expect } from 'chai';

class MyClass {
  add(x: number, y: number): number {
    return x + y;
  }
}

describe('MyClass', () => {
  let myClass: MyClass;

  beforeEach(() => {
    myClass = new MyClass();
  });

  it('should add two numbers', () => {
    const result = myClass.add(2, 3);
    expect(result).to.equal(5);
  });
});


In this example, we define a class MyClass with a method add that adds two numbers. We then use the describe function to create a test suite for the MyClass class. Inside the test suite, we use the beforeEach function to create an instance of the MyClass class before each test. We then use the it function to define a test case that checks if the add method works correctly.


You can run this test using Mocha in the terminal by running mocha --require ts-node/register test-file.ts (assuming you have TypeScript set up in your project).