Force error function for unit test

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() // 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.

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.

+4
2

@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 , .

, .

0

, .

try {
  yielded.value();
} catch (e){
  iter.throw(e);
}

.throw yield.

0

All Articles