addMethod.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*!
  2. * Chai - addMethod utility
  3. * Copyright(c) 2012-2014 Jake Luer <jake@alogicalparadox.com>
  4. * MIT Licensed
  5. */
  6. var config = require('../config');
  7. /**
  8. * ### .addMethod (ctx, name, method)
  9. *
  10. * Adds a method to the prototype of an object.
  11. *
  12. * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) {
  13. * var obj = utils.flag(this, 'object');
  14. * new chai.Assertion(obj).to.be.equal(str);
  15. * });
  16. *
  17. * Can also be accessed directly from `chai.Assertion`.
  18. *
  19. * chai.Assertion.addMethod('foo', fn);
  20. *
  21. * Then can be used as any other assertion.
  22. *
  23. * expect(fooStr).to.be.foo('bar');
  24. *
  25. * @param {Object} ctx object to which the method is added
  26. * @param {String} name of method to add
  27. * @param {Function} method function to be used for name
  28. * @name addMethod
  29. * @api public
  30. */
  31. var flag = require('./flag');
  32. module.exports = function (ctx, name, method) {
  33. ctx[name] = function () {
  34. var old_ssfi = flag(this, 'ssfi');
  35. if (old_ssfi && config.includeStack === false)
  36. flag(this, 'ssfi', ctx[name]);
  37. var result = method.apply(this, arguments);
  38. return result === undefined ? this : result;
  39. };
  40. };