1

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);
   done();
});

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 ?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
harshit
  • 7,925
  • 23
  • 70
  • 97

1 Answers1

3

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"))
};
expect(testFunc).to.throw(Error);
robertklep
  • 198,204
  • 35
  • 394
  • 381
  • I am getting this error, while running this test: TypeError: expect(...).to.throw is not a function. – Bharthan Feb 13 '19 at 16:59