How to throw error in node.js and catch it in mocha?

by edmond_brakus , in category: Javascript , 7 months ago

How to throw error in node.js and catch it in mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 7 months ago

@edmond_brakus 

To throw an error in Node.js and catch it in Mocha, you can follow these steps:

  1. In your Node.js code, you can throw an error using the throw keyword. For example:
1
2
3
4
5
6
function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}


  1. In your Mocha test file, you can use the expect function along with toThrow to check if the error is thrown when the function is called with invalid parameters. For example:
1
2
3
4
5
6
7
const expect = require('chai').expect;

describe('divide', () => {
  it('should throw an error when dividing by zero', () => {
    expect(() => divide(10, 0)).to.throw('Cannot divide by zero');
  });
});


In the above example, the test should throw an error when dividing by zero uses the expect function to call the divide function with invalid parameters (10 and 0) and checks if it throws an error with the message 'Cannot divide by zero'.


By following these steps, you can throw an error in Node.js and catch it in Mocha to test the expected behavior when an error occurs in your code.

Related Threads:

How to manually catch error exception in laravel?
How to debug node.js/mocha test built with makefile?
How to debug an "error: script error. (:0)" from mocha?
How to test promise catch with mocha.js?
How to test for a specific error message in mocha?
How to write code coverage for error block in mocha chai?