DEV Community 👩‍💻👨‍💻

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

Posted on

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 (2)

Collapse
heverton profile image
hevertonam

top man! ;) Parabens!

Funciona no yarm também ?

Collapse
luizcalaca profile image
Luiz Calaça Author

Funciona, sim!

🤔 Did you know?

 
🌚 Dark mode is available in Settings.