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

by edmond_brakus , in category: Javascript , 3 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 3 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.