I am trying to use unit test this Coa middleware:
function * onError(next) {
try {
yield next
} catch (err) {
this.status = 500
this.body = err.message
}
}
I want to call a catch block, but I cannot force to yield nextcause an error.
If it were a method without a generator, I would do something like this:
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)
Back to the generator function, because it is nextnot called (this is given), catch is not introduced.
I can access it next, but calling it is not enough, it throws its error outside of try:
function next() {
throw new Error('Boom?')
}
const iter = onError(next)
const yielded = iter.next()
console.log(yielded.value)
yielded.value()
So, to the question I want to answer, can I force execution in the catch block and, therefore, check my error handling?
If something is unclear, ask in the comments. Thank.