Как проверить на ошибку, сгенерированную в конструкторе? - PullRequest
0 голосов
/ 18 апреля 2020

Я пытаюсь отловить ошибку, сгенерированную в конструкторе, с помощью моего теста 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`);
    }
  }
}

Конструктор правильно выдает ошибку, однако тест ее не отлавливает:

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

Можно ли даже ловить ошибки, сгенерированные в конструкторе, с помощью chai?

1 Ответ

1 голос
/ 18 апреля 2020

Вы можете заключить создание объекта в вызов функции и затем ожидать, что будет сгенерировано исключение.

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

См. related answer.

...