addProperty.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*!
  2. * Chai - addProperty utility
  3. * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * ### addProperty (ctx, name, getter)
  8. *
  9. * Adds a property to the prototype of an object.
  10. *
  11. * utils.addProperty(chai.Assertion.prototype, 'foo', function () {
  12. * var obj = utils.flag(this, 'object');
  13. * new chai.Assertion(obj).to.be.instanceof(Foo);
  14. * });
  15. *
  16. * Can also be accessed directly from `chai.Assertion`.
  17. *
  18. * chai.Assertion.addProperty('foo', fn);
  19. *
  20. * Then can be used as any other assertion.
  21. *
  22. * expect(myFoo).to.be.foo;
  23. *
  24. * @param {Object} ctx object to which the property is added
  25. * @param {String} name of property to add
  26. * @param {Function} getter function to be used for name
  27. * @name addProperty
  28. * @api public
  29. */
  30. module.exports = function (ctx, name, getter) {
  31. Object.defineProperty(ctx, name,
  32. { get: function () {
  33. var result = getter.call(this);
  34. return result === undefined ? this : result;
  35. }
  36. , configurable: true
  37. });
  38. };