节点:在接受参数的函数上使用 chai 的 expect.to.throw
node: using chai's expect.to.throw on a function that takes arguments
我需要在一个带参数的函数上调用 expect().to.throw()
。例如,假设我有以下内容:
var func = function(x) {
if (x > 1) {
throw new Error()
} else {
console.log('hello')
}
}
expect(func).to.throw()
这会失败,因为它调用 func
时没有参数,这意味着它永远不会抛出错误。但是如果我调用 expect(func(2)).to.throw()
,我会得到 AssertionError: expected undefined to be a function
。该函数被调用并且 return 值被传递给 expect
.
如何使用 expect().to.throw()
并给出包含的函数参数。是使用匿名函数的唯一方法,例如 expect(() => {func(2)}).to.throw()
?
这是来自 chai docs:
If you need to assert that your function fn throws when passed certain arguments, then wrap a call to fn inside of another function.
expect(function () { fn(42); }).to.throw(); // Function expression
expect(() => fn(42)).to.throw(); // ES6 arrow function
我需要在一个带参数的函数上调用 expect().to.throw()
。例如,假设我有以下内容:
var func = function(x) {
if (x > 1) {
throw new Error()
} else {
console.log('hello')
}
}
expect(func).to.throw()
这会失败,因为它调用 func
时没有参数,这意味着它永远不会抛出错误。但是如果我调用 expect(func(2)).to.throw()
,我会得到 AssertionError: expected undefined to be a function
。该函数被调用并且 return 值被传递给 expect
.
如何使用 expect().to.throw()
并给出包含的函数参数。是使用匿名函数的唯一方法,例如 expect(() => {func(2)}).to.throw()
?
这是来自 chai docs:
If you need to assert that your function fn throws when passed certain arguments, then wrap a call to fn inside of another function.
expect(function () { fn(42); }).to.throw(); // Function expression
expect(() => fn(42)).to.throw(); // ES6 arrow function