spy_registry.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = SpyRegistry;
  6. var _call_tracker = require('./call_tracker');
  7. var _call_tracker2 = _interopRequireDefault(_call_tracker);
  8. var _create_spy = require('./create_spy');
  9. var _create_spy2 = _interopRequireDefault(_create_spy);
  10. var _spy_strategy = require('./spy_strategy');
  11. var _spy_strategy2 = _interopRequireDefault(_spy_strategy);
  12. function _interopRequireDefault(obj) {
  13. return obj && obj.__esModule ? obj : {default: obj};
  14. }
  15. const formatErrorMsg = (domain, usage) => {
  16. const usageDefinition = usage ? '\nUsage: ' + usage : '';
  17. return msg => domain + ' : ' + msg + usageDefinition;
  18. };
  19. /**
  20. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  21. *
  22. * This source code is licensed under the MIT license found in the
  23. * LICENSE file in the root directory of this source tree.
  24. *
  25. */
  26. // This file is a heavily modified fork of Jasmine. Original license:
  27. /*
  28. Copyright (c) 2008-2016 Pivotal Labs
  29. Permission is hereby granted, free of charge, to any person obtaining
  30. a copy of this software and associated documentation files (the
  31. "Software"), to deal in the Software without restriction, including
  32. without limitation the rights to use, copy, modify, merge, publish,
  33. distribute, sublicense, and/or sell copies of the Software, and to
  34. permit persons to whom the Software is furnished to do so, subject to
  35. the following conditions:
  36. The above copyright notice and this permission notice shall be
  37. included in all copies or substantial portions of the Software.
  38. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  39. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  40. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  41. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  42. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  43. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  44. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  45. */
  46. function isSpy(putativeSpy) {
  47. if (!putativeSpy) {
  48. return false;
  49. }
  50. return (
  51. putativeSpy.and instanceof _spy_strategy2.default &&
  52. putativeSpy.calls instanceof _call_tracker2.default
  53. );
  54. }
  55. const getErrorMsg = formatErrorMsg('<spyOn>', 'spyOn(<object>, <methodName>)');
  56. function SpyRegistry(options) {
  57. options = options || {};
  58. const currentSpies =
  59. options.currentSpies ||
  60. function() {
  61. return [];
  62. };
  63. this.allowRespy = function(allow) {
  64. this.respy = allow;
  65. };
  66. this.spyOn = function(obj, methodName, accessType) {
  67. if (accessType) {
  68. return this._spyOnProperty(obj, methodName, accessType);
  69. }
  70. if (obj === void 0) {
  71. throw new Error(
  72. getErrorMsg(
  73. 'could not find an object to spy upon for ' + methodName + '()'
  74. )
  75. );
  76. }
  77. if (methodName === void 0) {
  78. throw new Error(getErrorMsg('No method name supplied'));
  79. }
  80. if (obj[methodName] === void 0) {
  81. throw new Error(getErrorMsg(methodName + '() method does not exist'));
  82. }
  83. if (obj[methodName] && isSpy(obj[methodName])) {
  84. if (this.respy) {
  85. return obj[methodName];
  86. } else {
  87. throw new Error(
  88. getErrorMsg(methodName + ' has already been spied upon')
  89. );
  90. }
  91. }
  92. let descriptor;
  93. try {
  94. descriptor = Object.getOwnPropertyDescriptor(obj, methodName);
  95. } catch (e) {
  96. // IE 8 doesn't support `definePropery` on non-DOM nodes
  97. }
  98. if (descriptor && !(descriptor.writable || descriptor.set)) {
  99. throw new Error(
  100. getErrorMsg(methodName + ' is not declared writable or has no setter')
  101. );
  102. }
  103. const originalMethod = obj[methodName];
  104. const spiedMethod = (0, _create_spy2.default)(methodName, originalMethod);
  105. let restoreStrategy;
  106. if (Object.prototype.hasOwnProperty.call(obj, methodName)) {
  107. restoreStrategy = function() {
  108. obj[methodName] = originalMethod;
  109. };
  110. } else {
  111. restoreStrategy = function() {
  112. if (!delete obj[methodName]) {
  113. obj[methodName] = originalMethod;
  114. }
  115. };
  116. }
  117. currentSpies().push({
  118. restoreObjectToOriginalState: restoreStrategy
  119. });
  120. obj[methodName] = spiedMethod;
  121. return spiedMethod;
  122. };
  123. this._spyOnProperty = function(obj, propertyName) {
  124. let accessType =
  125. arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'get';
  126. if (!obj) {
  127. throw new Error(
  128. getErrorMsg('could not find an object to spy upon for ' + propertyName)
  129. );
  130. }
  131. if (!propertyName) {
  132. throw new Error(getErrorMsg('No property name supplied'));
  133. }
  134. let descriptor;
  135. try {
  136. descriptor = Object.getOwnPropertyDescriptor(obj, propertyName);
  137. } catch (e) {
  138. // IE 8 doesn't support `definePropery` on non-DOM nodes
  139. }
  140. if (!descriptor) {
  141. throw new Error(getErrorMsg(propertyName + ' property does not exist'));
  142. }
  143. if (!descriptor.configurable) {
  144. throw new Error(
  145. getErrorMsg(propertyName + ' is not declared configurable')
  146. );
  147. }
  148. if (!descriptor[accessType]) {
  149. throw new Error(
  150. getErrorMsg(
  151. 'Property ' +
  152. propertyName +
  153. ' does not have access type ' +
  154. accessType
  155. )
  156. );
  157. }
  158. if (obj[propertyName] && isSpy(obj[propertyName])) {
  159. if (this.respy) {
  160. return obj[propertyName];
  161. } else {
  162. throw new Error(
  163. getErrorMsg(propertyName + ' has already been spied upon')
  164. );
  165. }
  166. }
  167. const originalDescriptor = descriptor;
  168. const spiedProperty = (0, _create_spy2.default)(
  169. propertyName,
  170. descriptor[accessType]
  171. );
  172. let restoreStrategy;
  173. if (Object.prototype.hasOwnProperty.call(obj, propertyName)) {
  174. restoreStrategy = function() {
  175. Object.defineProperty(obj, propertyName, originalDescriptor);
  176. };
  177. } else {
  178. restoreStrategy = function() {
  179. delete obj[propertyName];
  180. };
  181. }
  182. currentSpies().push({
  183. restoreObjectToOriginalState: restoreStrategy
  184. });
  185. const spiedDescriptor = Object.assign({}, descriptor, {
  186. [accessType]: spiedProperty
  187. });
  188. Object.defineProperty(obj, propertyName, spiedDescriptor);
  189. return spiedProperty;
  190. };
  191. this.clearSpies = function() {
  192. const spies = currentSpies();
  193. for (let i = spies.length - 1; i >= 0; i--) {
  194. const spyEntry = spies[i];
  195. spyEntry.restoreObjectToOriginalState();
  196. }
  197. };
  198. }