overwriteProperty.js 1.5 KB

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