@edmond_brakus
To throw an error in Node.js and catch it in Mocha, you can follow these steps:
1 2 3 4 5 6 |
function divide(a, b) { if (b === 0) { throw new Error('Cannot divide by zero'); } return a / b; } |
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.