Javascript 强制已屈服的函数出错以进行单元测试 我尝试对这个膝关节炎的中间件进行单元测试: function * onError(next) { try { yield next } catch (err) { this.status = 500 this.body = err.message } }
我希望触发catch块,但我似乎无法让Javascript 强制已屈服的函数出错以进行单元测试 我尝试对这个膝关节炎的中间件进行单元测试: function * onError(next) { try { yield next } catch (err) { this.status = 500 this.body = err.message } },javascript,unit-testing,ecmascript-6,generator,Javascript,Unit Testing,Ecmascript 6,Generator,我希望触发catch块,但我似乎无法让yield next导致错误 如果这是一种非生成器方法,我会这样做: function method (next) { try { next() } catch(err) { this.xxx = 'Error = ' + err.message } } function next() { throw new Error('Boom!') } const context = {} method
yield next
导致错误
如果这是一种非生成器方法,我会这样做:
function method (next) {
try {
next()
} catch(err) {
this.xxx = 'Error = ' + err.message
}
}
function next() {
throw new Error('Boom!')
}
const context = {}
method.bind(context)(next)
console.log("Expect context to contain xxx with error message")
console.log(context.xxx)
返回generator函数,因为未调用next
(它已屈服于),所以未输入捕获
我可以访问next
,但调用它是不够的,它会在try之外抛出错误:
function next() {
throw new Error('Boom?')
}
const iter = onError(next)
const yielded = iter.next() // Moves the generator to the first, and only, yield
console.log(yielded.value) // Our next
yielded.value() // Error is thrown here, not in the generator.
所以,我想回答的问题是,我可以强制执行catch块,从而测试我的错误处理吗
如果有什么不清楚的地方,请在评论中询问。谢谢。您需要将错误传递回生成器,例如
try {
yielded.value();
} catch (e){
iter.throw(e);
}
在生成器上调用
.throw
将导致从当前挂起的yield
语句中抛出一个值。在@loganfsmyth提到iterator.throw()
之后,我想到了以下几点:
// Function to test
function * onError(next) {
try {
yield next
} catch (err) {
this.status = 500
this.body = err.message
}
}
// Context we expect to be updated in the catch block
const context = {}
// Get the generator
const iter = onError.bind(context)()
// Move generator to first yield
iter.next()
// Pass an error into the generator
iter.throw(err)
// Check the context
expect(context.status).to.equal(500)
我在迭代器上尝试了调用throw
和next
的其他组合,但不是这个
内联注释解释了所发生的事情。也许我遗漏了一些东西,因为我还没有真正深入了解生成器函数,但我看不到
yield next
可以加入规范的任何方法:(稍微向下滚动到“yield
AssignmentExpression”)。我认为抛出的唯一机会是计算AssignmentExpression,但在您的示例中计算next
不会抛出。因此,如果我没有能力在try块中控制next
,我就不能输入catch?我是说我对规范的读取(可能不正确)无论next
函数做什么(实际上,不管它是否是函数),都不会抛出yield next
yield next
将暂停生成器并返回next
的值。这就是全部。它不会运行next
。抱歉,误读了您的第一条评论。这就是我看到的。我试着传入一个错误,未定义和一个函数,包括普通和生成器。正如你所说,它不会继续。谢谢@loganfsmyth-你提示我返回并再次尝试throw
!