0

I'm trying to catch an error thrown in the constructor with my chai test:

'use strict'

const chai = require('chai')
const expect = chai.expect

describe('A rover must be placed inside the platform', function() {
  it('A Rover at position -1 2 S should throw an error', function() {
    expect(new Rover(-1, 2, 'N')).should.throw(Error ('Rover has landed outside of the platform'));
  })
})


class Rover {
  constructor(x, y, heading) {
    this.x = x;
    this.y = y;
    this.heading = heading;

    if (this.x > 5 || this.x < 0 || this.y > 5 || this.y < 0) {
      throw Error(`Rover has landed outside of the platform`);
    }
  }
}

The constructor correctly throws the error, however the test doesn't catch it:

A rover must be placed inside the platform
    1) A Rover at position -1 2 S should throw an error


  1 failing

  1) A rover must be placed inside the platform
       A Rover at position -1 2 S should throw an error:
     Error: Rover has landed outside of the platform

Is it even possible to catch Errors thrown in the Constructor with chai?

mles
  • 4,534
  • 10
  • 54
  • 94
  • 1
    You do this the same way you test *anything* that throws an error - defer execution. See the docs and e.g. https://stackoverflow.com/questions/36216868/how-to-test-for-thrown-error-with-chai-should – jonrsharpe Apr 18 '20 at 14:22

1 Answers1

1

You can wrap the object creation in a function call and then expect the exception to be thrown.

expect(function () {
    new Rover(-1, 2, 'N');
}).to.throw('Rover has landed outside of the platform');

See related answer.

mles
  • 4,534
  • 10
  • 54
  • 94
Prasanth
  • 5,230
  • 2
  • 29
  • 61