Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ChaiJS期望构造函数抛出错误_Javascript_Ruby On Rails_Testing_Chai - Fatal编程技术网

Javascript ChaiJS期望构造函数抛出错误

Javascript ChaiJS期望构造函数抛出错误,javascript,ruby-on-rails,testing,chai,Javascript,Ruby On Rails,Testing,Chai,我试图测试我的构造函数是否会使用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:

我试图测试我的构造函数是否会使用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');
  });

我也有同样的问题。用函数包装构造函数:

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

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

对于在构造函数中测试抛出消息错误,可以使用mocha和chai编写此测试(使用ES6语法):


请参阅Diego A.Zapata Häntsch()的这支笔,以检查上述代码的实时工作。

这是不是意味着
expect(badConstructor())
?你需要调用这个函数。我刚刚试过,但没有用。现在我得到了另一个错误输出——我在OP中添加了它。所以听起来它工作正常,因为“无效位置”是错误消息的一部分。您可能需要在测试中选择它,或者在函数中添加一个
try/catch
语句来返回一个您可以测试的错误。但是不应该期望它抛出一个错误吗?请注意,我不需要try/catch?它是返回一个错误tho还是只是将一些内容记录到控制台?我打赌是后者。避免
函数(完成)
。那么你就不需要那个方法调用并保存一行了哦,这很简单但很聪明!
var fcn = function(){new badConstructor()};
expect(fcn).to.throw(Error, 'Invalid location');
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')
})
'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/);
  });
});