【问题标题】:ChaiJS expect constructor to throw errorChaiJS 期望构造函数抛出错误
【发布时间】:2015-05-11 19:30:10
【问题描述】:

我正在尝试使用 Teaspoon gem for Rails 测试我的构造函数是否会引发错误,并使用 ChaiJS 作为我的断言库。

当我运行以下测试时:

  it('does not create the seat if x < 0', function() {
    var badConstructor = function() {
      return new Seat({ radius: 10, x: -0.1, y: 0.2, seat_number: 20, table_number: 30});
    };

    expect(badConstructor).to.throw(Error, 'Invalid location');
  });

我得到这个输出:

失败:

  1) Seat does not create the seat if x < 0
     Failure/Error: undefined is not a constructor (evaluating 'expect(badConstructor).to.throw(Error(), 'Invalid location')')

构造函数抛出错误,但我认为我没有正确编写测试。

当我尝试运行 expect(badConstructor()) 时,我得到了输出:

Failures:

  1) Seat does not create the seat if x < 0
     Failure/Error: Invalid location

【问题讨论】:

  • expect(badConstructor())吗?即,您需要调用该函数。
  • 我刚刚尝试过 - 无济于事。现在我得到另一个错误输出 - 我在 OP 中添加了它。
  • 所以听起来它工作正常,因为“无效位置”是错误消息的一部分。你要么需要在你的测试中选择它,要么在你的函数中添加一个try/catch 语句来返回一个你可以测试的错误。
  • 但不应该指望它抛出一个错误照顾我不需要 try/catch 吗?
  • 它是返回错误还是只是将某些内容记录到控制台?我敢打赌后者。

标签: javascript ruby-on-rails testing chai


【解决方案1】:

遇到了同样的问题。用函数包装你的构造函数:

var fcn = function(){new badConstructor()};
expect(fcn).to.throw(Error, 'Invalid location');

【讨论】:

  • 哦,这很简单但很聪明!
【解决方案2】:

为了在构造函数中测试抛出消息错误,你可以使用 mocha 和 chai 编写这个测试(使用 ES6 语法):

'use strict';
// ES6 class definition
class A {
  constructor(msg) {
    if(!msg) throw new Error('Give me the message');
    this.message = msg;
  }
}

// test.js
describe('A constructor', function() {
  it('Should throw an error with "Give me the message" text if msg is null', function() {
    (() => new A()).should.throw(Error, /Give me the message/);
  });
});
请参阅此笔以检查上述代码 zJppaj 的实时工作,作者 Diego A. Zapata Häntsch (@diegoazh) 在 CodePen 上。

【讨论】:

  • 避免function(done)。然后您将不需要该方法调用并保存一行
【解决方案3】:

完整示例:

function fn(arg) {
  if (typeof arg !== 'string')
    throw TypeError('Must be an string')

  return { arg: arg }
}

it('#fn', function () {
  expect(fn).to.throw(TypeError)
  expect(fn.bind(2)).to.throw(TypeError)
  expect(fn('str')).to.be.equal('str')
})

【讨论】:

    猜你喜欢
    • 2017-03-24
    • 2017-12-06
    • 2023-02-08
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多