如何测试在构造函数中引发的错误?

问题描述 投票:1回答:1

我正在尝试使用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捕获在构造方法中抛出的错误吗?

javascript chai
1个回答
0
投票

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

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

请参阅related答案。

© www.soinside.com 2019 - 2024. All rights reserved.