jasmine-async.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // https://github.com/mout/mout/blob/master/tests/lib/jasmine/jasmine.async.js
  2. // borrowed from jasmine-node
  3. // makes async tests easier
  4. // https://github.com/mhevery/jasmine-node
  5. // released under MIT license
  6. (function() {
  7. var withoutAsync = {};
  8. function monkeyPatch(jasmineFunction) {
  9. withoutAsync[jasmineFunction] = jasmine.Env.prototype[jasmineFunction];
  10. return jasmine.Env.prototype[jasmineFunction] = function() {
  11. var args = Array.prototype.slice.call(arguments, 0);
  12. var timeout = null;
  13. if (isLastArgumentATimeout(args)) {
  14. timeout = args.pop();
  15. }
  16. if (isLastArgumentAnAsyncSpecFunction(args))
  17. {
  18. var specFunction = args.pop();
  19. args.push(function() {
  20. return asyncSpec(specFunction, this, timeout);
  21. });
  22. }
  23. return withoutAsync[jasmineFunction].apply(this, args);
  24. };
  25. }
  26. // since oldIE doesn't support forEach
  27. monkeyPatch('it');
  28. monkeyPatch('beforeEach');
  29. monkeyPatch('afterEach');
  30. function isLastArgumentATimeout(args)
  31. {
  32. return args.length > 0 && (typeof args[args.length-1]) === "number";
  33. }
  34. function isLastArgumentAnAsyncSpecFunction(args)
  35. {
  36. return args.length > 0 && (typeof args[args.length-1]) === "function" && args[args.length-1].length > 0;
  37. }
  38. function asyncSpec(specFunction, spec, timeout) {
  39. if (timeout == null) timeout = jasmine.DEFAULT_TIMEOUT_INTERVAL || 1000;
  40. var done = false;
  41. spec.runs(function() {
  42. try {
  43. return specFunction(function(error) {
  44. done = true;
  45. if (error != null) return spec.fail(error);
  46. });
  47. } catch (e) {
  48. done = true;
  49. throw e;
  50. }
  51. });
  52. return spec.waitsFor(function() {
  53. if (done === true) {
  54. return true;
  55. }
  56. }, "spec to complete", timeout);
  57. };
  58. }).call(this);