RavenHursT February 2016

How Do I Test nested ES6 Generators using Mocha?

I'm trying to use co-mocha to test some nested generators functionality in my koa app. The class works just fine at runtime, but when I attempt to test the functionality, I cannot get the nested generator to run in my test.

Class being tested:

import Promise from 'bluebird'

class FooService {
  _doAsync(){
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          foo: 'FOO'
        })
      }, 500)
    })
  }

  create(){
    console.log('This never gets logged')
    let self = this
    return function*(){
      console.log(`This doesn't either`)
      return yield self._doAsync()
    }
  }
}
export default new FooService()

Test File

import fooService '../services/foo-service'
import Chai from 'chai'
let expect = Chai.expect

describe('Testing generators', () => {
  it('Should just work', function *(){
    console.log('This log never happens')
    let result = yield fooService.create()
    expect(result).to.equal({foo: 'FOO'})
  })
})

I'm running mocha w/ --require co-mocha and Node 4.2.6

While the tests complete w/o errors, NONE of the console above ever get logged and so I'm quite sure the actual test generator is never running at all.

If I try using the npm package, mocha-generators instead, while I get the log from inside the test generator, the underlying generator returned from the create() method on the service never fires...

What am I doing wrong??

Answers


Bergi February 2016

Without mocha-generators, the it callback returns a generator that will not be run by anyone. You'd need to wrap it in co manually so that mocha would receive a promise.

With mocha-generators, your generator is executed but yields a generator function. That's not expected, you are supposed to yield promises. You need to call the generator function that the create() call returns yourself, and then you shouldn't yield a generator itself but rather delegate to it via yield*:

let result = yield* fooService.create()();

Post Status

Asked in February 2016
Viewed 2,460 times
Voted 11
Answered 1 times

Search




Leave an answer