overwriteMethod.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*!
  2. * Chai - overwriteMethod utility
  3. * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * ### overwriteMethod (ctx, name, fn)
  8. *
  9. * Overwites an already existing method and provides
  10. * access to previous function. Must return function
  11. * to be used for name.
  12. *
  13. * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) {
  14. * return function (str) {
  15. * var obj = utils.flag(this, 'object');
  16. * if (obj instanceof Foo) {
  17. * new chai.Assertion(obj.value).to.equal(str);
  18. * } else {
  19. * _super.apply(this, arguments);
  20. * }
  21. * }
  22. * });
  23. *
  24. * Can also be accessed directly from `chai.Assertion`.
  25. *
  26. * chai.Assertion.overwriteMethod('foo', fn);
  27. *
  28. * Then can be used as any other assertion.
  29. *
  30. * expect(myFoo).to.equal('bar');
  31. *
  32. * @param {Object} ctx object whose method is to be overwritten
  33. * @param {String} name of method to overwrite
  34. * @param {Function} method function that returns a function to be used for name
  35. * @name overwriteMethod
  36. * @api public
  37. */
  38. module.exports = function (ctx, name, method) {
  39. var _method = ctx[name]
  40. , _super = function () { return this; };
  41. if (_method && 'function' === typeof _method)
  42. _super = _method;
  43. ctx[name] = function () {
  44. var result = method(_super).apply(this, arguments);
  45. return result === undefined ? this : result;
  46. }
  47. };