async-callback.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*global jasmine: true */
  2. (function() {
  3. var withoutAsync = {};
  4. ["it", "beforeEach", "afterEach"].forEach(function(jasmineFunction) {
  5. withoutAsync[jasmineFunction] = jasmine.Env.prototype[jasmineFunction];
  6. return jasmine.Env.prototype[jasmineFunction] = function() {
  7. var args = Array.prototype.slice.call(arguments, 0);
  8. var timeout = null;
  9. if (isLastArgumentATimeout(args)) {
  10. timeout = args.pop();
  11. }
  12. if (isLastArgumentAnAsyncSpecFunction(args))
  13. {
  14. var specFunction = args.pop();
  15. args.push(function() {
  16. return asyncSpec(specFunction, this, timeout);
  17. });
  18. }
  19. return withoutAsync[jasmineFunction].apply(this, args);
  20. };
  21. });
  22. function isLastArgumentATimeout(args)
  23. {
  24. return args.length > 0 && (typeof args[args.length-1]) === "number";
  25. }
  26. function isLastArgumentAnAsyncSpecFunction(args)
  27. {
  28. return args.length > 0 && (typeof args[args.length-1]) === "function" && args[args.length-1].length > 0;
  29. }
  30. function asyncSpec(specFunction, spec, timeout) {
  31. if (timeout == null){timeout = jasmine.DEFAULT_TIMEOUT_INTERVAL || 1000;}
  32. var done = false;
  33. spec.runs(function() {
  34. try {
  35. return specFunction(function(error) {
  36. done = true;
  37. if (error != null) {
  38. return spec.fail(error);
  39. }
  40. });
  41. } catch (e) {
  42. done = true;
  43. throw e;
  44. }
  45. });
  46. return spec.waitsFor(function() {
  47. if (done === true) {
  48. return true;
  49. }
  50. }, "spec to complete", timeout);
  51. }
  52. }).call(this);