Javascript 如何测试构造函数中抛出的错误?

Javascript 如何测试构造函数中抛出的错误?,javascript,chai,Javascript,Chai,我正试图用我的chai测试捕获构造函数中抛出的错误: '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

我正试图用我的chai测试捕获构造函数中抛出的错误:

'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`);
    }
  }
}

甚至可以用chai捕捉构造函数中抛出的错误吗?

您可以将对象创建包装在函数调用中,然后期望抛出异常

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

请参阅答案。

执行此操作的方法与测试任何抛出错误的方法相同-延迟执行。参见文档和示例。
expect(function () {
    new Rover(-1, 2, 'N');
}).to.throw('Rover has landed outside of the platform');