MochaWrapper.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var domain = require('domain');
  2. var fs = require('fs');
  3. var path = require('path');
  4. var Mocha = require('mocha');
  5. function MochaWrapper(params) {
  6. // If require option is specified then require that file.
  7. // This code has been adapted from the treatment of the require
  8. // option in the mocha source (bin/_mocha)
  9. var cwd = process.cwd();
  10. var join = path.join;
  11. var resolve = path.resolve;
  12. var exists = fs.existsSync;
  13. module.paths.push(cwd, join(cwd, 'node_modules'));
  14. if (params.options && params.options.require) {
  15. var mods = params.options.require instanceof Array ? params.options.require : [params.options.require];
  16. mods.forEach(function(mod) {
  17. if (typeof mod === 'string') {
  18. var abs = exists(mod) || exists(mod + '.js');
  19. if (abs) {
  20. mod = resolve(mod);
  21. }
  22. require(mod);
  23. } else if (typeof mod === 'function') {
  24. mod();
  25. }
  26. });
  27. }
  28. var mocha = new Mocha(params.options);
  29. var filterFunc = params.options.clearCacheFilter;
  30. if (params.options.clearRequireCache === true) {
  31. Object.keys(require.cache).forEach(function (key) {
  32. if (typeof filterFunc !== 'function' || !filterFunc(key)) {
  33. delete require.cache[key];
  34. }
  35. });
  36. }
  37. params.files.forEach(function(file) {
  38. file.src.forEach(mocha.addFile.bind(mocha));
  39. });
  40. this.run = function(callback) {
  41. try {
  42. mocha.run(function(failureCount) {
  43. callback(null, failureCount);
  44. });
  45. } catch (error) {
  46. // catch synchronous (uncaught) exceptions thrown as a result
  47. // of loading the test files so that they can be reported with
  48. // better details
  49. callback(error);
  50. }
  51. };
  52. }
  53. module.exports = MochaWrapper;