overwriteChainableMethod.js 1.7 KB

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