【问题标题】:Throw exception in superclass does not work在超类中抛出异常不起作用
【发布时间】:2020-07-07 16:48:45
【问题描述】:

我正在使用带有以下类的 javascript:

class A {
  constructor(config) {
    if (_.isEmpty(config) || !_.isObject(config)) {
      throw new Error('config cannot be null');
    }
  }
}

class B extends A {
  constructor(config) {
    super(config);
  }
}

我正在运行以下测试:

describe('B', function () {
    it('Should throw an error if instantiated without a config.', function () {
      expect(function () {
        const cs = new B(null);
      }).to.throw();
    });
  });

问题是没有抛出异常,

如果我不扩展 A 类并在 B 中抛出异常,则测试通过

提前致谢

【问题讨论】:

  • 这很奇怪,你确定你是在扩展同一个 A 类而不是另一个?
  • 感谢您的回答!问题在于 beforeEach 函数将配置设置为不同于 null 的值。

标签: javascript inheritance


【解决方案1】:

我认为这不是继承问题。我在 node.js REPL 中运行了它,它抛出了预期的错误:

> class A {
... constructor(config) {
..... if (config == null) {
....... throw new Error('config cannot be null');
....... }
..... }
... }
undefined
> class B extends A {
... constructor(config) {
..... super(config);
..... }
... }
undefined
> new B(null);
Error: config cannot be null
    at new A (repl:4:7)
    at new B (repl:3:1)
>

问题可能不是您对继承的使用。也许你的 lodash 检查、浏览器有问题,或者 Babel 的转译问题。或者AB 可能不是你想象的那样。

【讨论】:

  • 感谢您的回答!问题在于 beforeEach 函数将配置设置为不同于 null 的值。
猜你喜欢
  • 2019-09-29
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 2021-03-15
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
相关资源
最近更新 更多