co-mocha.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. var co = require('co')
  2. var isGenFn = require('is-generator').fn
  3. /**
  4. * Export `co-mocha`.
  5. */
  6. module.exports = coMocha
  7. /**
  8. * Monkey patch the mocha instance with generator support.
  9. *
  10. * @param {Function} mocha
  11. */
  12. function coMocha (mocha) {
  13. // Avoid loading `co-mocha` twice.
  14. if (!mocha || mocha._coMochaIsLoaded) {
  15. return
  16. }
  17. var Runnable = mocha.Runnable
  18. var run = Runnable.prototype.run
  19. /**
  20. * Override the Mocha function runner and enable generator support with co.
  21. *
  22. * @param {Function} fn
  23. */
  24. Runnable.prototype.run = function (fn) {
  25. var oldFn = this.fn
  26. if (isGenFn(oldFn)) {
  27. this.fn = co.wrap(oldFn)
  28. // Replace `toString` to output the original function contents.
  29. this.fn.toString = function () {
  30. // https://github.com/mochajs/mocha/blob/7493bca76662318183e55294e906a4107433e20e/lib/utils.js#L251
  31. return Function.prototype.toString.call(oldFn)
  32. .replace(/^function *\* *\(.*\)\s*{/, 'function () {')
  33. }
  34. }
  35. return run.call(this, fn)
  36. }
  37. mocha._coMochaIsLoaded = true
  38. }
  39. /**
  40. * Find active node mocha instances.
  41. *
  42. * @return {Array}
  43. */
  44. function findNodeJSMocha () {
  45. var children = require.cache || {}
  46. return Object.keys(children)
  47. .filter(function (child) {
  48. var val = children[child].exports
  49. return typeof val === 'function' && val.name === 'Mocha'
  50. })
  51. .map(function (child) {
  52. return children[child].exports
  53. })
  54. }
  55. // Attempt to automatically monkey patch available mocha instances.
  56. var modules = typeof window === 'undefined' ? findNodeJSMocha() : [window.Mocha]
  57. modules.forEach(coMocha)