gpt4 book ai didi

javascript - Node : using chai's expect. to.throw 接受参数的函数

转载 作者:行者123 更新时间:2023-11-30 08:25:14 26 4
gpt4 key购买 nike

我需要在接受参数的函数上调用 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。调用该函数并将返回值传递给 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

关于javascript - Node : using chai's expect. to.throw 接受参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46774128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com