DEV Community

Cover image for Typescript boilerplate test configuration with mocha, chai and sinon
Luiz Calaça
Luiz Calaça

Posted on

5 1

Typescript boilerplate test configuration with mocha, chai and sinon

Hi, Devs!

Let's configure tests with mocha, chai and sinon on Typescript in a few steps.


Lets' start the project:

npm init -y
Enter fullscreen mode Exit fullscreen mode

Now, let's install the packages. Here we also install the types (@types) of each library because we need to use them on Typescript. Usually we need to test some elements that returns one promise, so we need do install chai-as-promised.

npm i -D mocha @types/mocha chai @types/chai 
npm i -D sinon @types/sinon
npm i -D chai-as-promised @types/chai-as-promised
Enter fullscreen mode Exit fullscreen mode

We need to use ts-node library to run our tests, because using Typescript we have to transpile the code. So let's install typescript and ts-node.

npm i -D typescript ts-node
Enter fullscreen mode Exit fullscreen mode

Now put on your package.json the necessary script to run the tests:

"scripts": {
  ...
  "test": "mocha --require ts-node/register tests/**/*.spec.ts --exit"
}
Enter fullscreen mode Exit fullscreen mode

Create one folder with the name tests, into a file with testfirst.spec.ts name and create a simple case:

import { describe } from "mocha";
import { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);
const expect = chai.expect;

describe('Testing the configuration', () => {
  it('should pass', () => {

  });
});
Enter fullscreen mode Exit fullscreen mode

After you could run:

npm run test
Enter fullscreen mode Exit fullscreen mode

That' all!

Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Top comments (3)

Collapse
 
heverton profile image
hevertonam

top man! ;) Parabens!

Funciona no yarm também ?

Collapse
 
luizcalaca profile image
Luiz Calaça

Funciona, sim!

Collapse
 
peter_nollmeier_ba83c5508 profile image
Peter Nollmeier

Hm, the example code doesn't seem to work anymore?

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay