How to use promise using mocha and chai?

by elise_daugherty , in category: Javascript , 2 months ago

How to use promise using mocha and chai?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 2 months ago

@elise_daugherty 

To use promises with Mocha and Chai, you can create asynchronous tests that return promises. Here's an example of how you can use promises with Mocha and Chai:

  1. Install Mocha and Chai using npm:
1
npm install --save-dev mocha chai


  1. Create a test file (e.g. test.js) and import Mocha and Chai:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const chai = require('chai');
const expect = chai.expect;

describe('Asynchronous Test', function() {
  it('should resolve the promise', function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        resolve('success');
      }, 1000);
    }).then(function(result) {
      expect(result).to.equal('success');
    });
  });

  it('should reject the promise', function() {
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        reject('error');
      }, 1000);
    }).catch(function(error) {
      expect(error).to.equal('error');
    });
  });
});


  1. Run the tests using Mocha:
1
npx mocha test.js


In the above example, we have created two asynchronous tests that return promises. The first test resolves the promise after a timeout of 1 second and asserts the result using Chai's expect. The second test rejects the promise after a timeout of 1 second and handles the error using the catch method.


Mocha will automatically wait for the promises to resolve or reject before completing the test, allowing you to write clean and readable asynchronous tests using promises with Chai assertions.