harshit harshit - 4 months ago 21x
Node.js Question

How to test of throwing exception in nodejs using mocha

here is my function

var EngineAction = function (hostUrl) {
this.parseInput = function (vinNumber, action) {
var requestedAction = ''
if (action === 'START') {
requestedAction = 'START_VEHICLE';
} else if (action === 'STOP') {
requestedAction = 'STOP_VEHICLE';
} else {
throw new Error("input action is not valid");
return { id: vinNumber, "action" : requestedAction };


Here is mocha test:

it('throw error, input for engineAction', function(done) {
var gm = new GM ();
expect(gm.engineAction.parseInput("123", "STATR")).to.throw(Error);
gm.engineAction.parseInput("123", "STATR")).to.throw(Error);

I have tried multiple ways but the test fails with the message

1) GM model test throw error, input for engineAction:
Error: input action is not valid
at parseInput (models/gm.js:87:15)
at Context.<anonymous> (test/gm.js:59:25)

This shows the method throws error but test is not asserting. What am i missing ?


You need to pass a function reference to expect.

Because you want to call your method with arguments, you need to create a partial function, pre-bound with the arguments:

expect(gm.engineAction.parseInput.bind(gm, "123", "STATR")).to.throw(Error);

(this uses gm to be the this variable in your method, which may or may not be right)

Alternatively, you can wrap your method with another function:

var testFunc = function() {
  gm.engineAction.parseInput("123", "STATR"))