How Do I Test nested ES6 Generators using Mocha?

假装没事ソ 提交于 2019-12-14 03:55:43

问题


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??


回答1:


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()();


来源:https://stackoverflow.com/questions/35280756/how-do-i-test-nested-es6-generators-using-mocha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!