index.js 725 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict'
  2. module.exports = function stubs(obj, method, cfg, stub) {
  3. if (!obj || !method || !obj[method])
  4. throw new Error('You must provide an object and a key for an existing method')
  5. if (!stub) {
  6. stub = cfg
  7. cfg = {}
  8. }
  9. stub = stub || function() {}
  10. cfg.callthrough = cfg.callthrough || false
  11. cfg.calls = cfg.calls || 0
  12. var norevert = cfg.calls === 0
  13. var cached = obj[method].bind(obj)
  14. obj[method] = function() {
  15. var args = [].slice.call(arguments)
  16. var returnVal
  17. if (cfg.callthrough)
  18. returnVal = cached.apply(obj, args)
  19. returnVal = stub.apply(obj, args) || returnVal
  20. if (!norevert && --cfg.calls === 0)
  21. obj[method] = cached
  22. return returnVal
  23. }
  24. }