How to test promise catch with mocha.js?

by aniya.jaskolski , in category: Javascript , 9 months ago

How to test promise catch with mocha.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 9 months ago

@aniya.jaskolski 

To test promise catch with mocha.js, you can use the chai-as-promised plugin to handle asynchronous promises in your tests. Here's an example of how you can write a test case for a promise catch:

  1. Install chai-as-promised package by running the following command in your terminal:
1
npm install chai-as-promised --save-dev


  1. In your test file, import chai, chai-as-promised, and mocha:
1
2
3
4
5
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const { expect } = chai;

chai.use(chaiAsPromised);


  1. Write a test case to test the promise catch block:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
describe('Promise Catch Test', () => {
    it('should catch an error in the promise', () => {
        // The promise that will throw an error
        const errorPromise = new Promise((resolve, reject) => {
            reject(new Error('Something went wrong'));
        });

        // Testing the promise catch block
        return expect(errorPromise).to.be.rejectedWith('Something went wrong');
    });
});


  1. Run your test file using mocha:
1
mocha yourTestFile.js


Your test should now run and check if the promise is properly catching the error. If the error is caught as expected, the test case should pass.

Related Threads:

How to test through a mocked promise with mocha?
How to test globals with mocha.js?
How to programmatically skip a test in mocha.js?
How to test d3.js with mocha.js?
How to test jquery code with mocha.js?
How to test pure javascript module with mocha.js?