test-errors.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const errors = require("sdk/deprecated/errors");
  6. exports.testCatchAndLog = function(assert) {
  7. var caught = [];
  8. function dummyLog(e) { caught.push(e); }
  9. var wrapped = errors.catchAndLog(function(x) {
  10. throw Error("blah" + x + this);
  11. }, "boop", dummyLog);
  12. assert.equal(wrapped.call("hi", 1), "boop",
  13. "exceptions should be trapped, def. resp. returned");
  14. assert.equal(caught.length, 1,
  15. "logging function should be called");
  16. assert.equal(caught[0].message, "blah1hi",
  17. "args and this should be passed to wrapped func");
  18. };
  19. exports.testCatchAndLogProps = function(assert) {
  20. var caught = [];
  21. function dummyLog(e) { caught.push(e); }
  22. var thing = {
  23. foo: function(x) { throw Error("nowai" + x); },
  24. bar: function() { throw Error("blah"); },
  25. baz: function() { throw Error("fnarg"); }
  26. };
  27. errors.catchAndLogProps(thing, "foo", "ugh", dummyLog);
  28. assert.equal(thing.foo(1), "ugh",
  29. "props should be wrapped");
  30. assert.equal(caught.length, 1,
  31. "logging function should be called");
  32. assert.equal(caught[0].message, "nowai1",
  33. "args should be passed to wrapped func");
  34. assert.throws(function() { thing.bar(); },
  35. /blah/,
  36. "non-wrapped props should be wrapped");
  37. errors.catchAndLogProps(thing, ["bar", "baz"], "err", dummyLog);
  38. assert.ok((thing.bar() == thing.baz()) &&
  39. (thing.bar() == "err"),
  40. "multiple props should be wrapped if array passed in");
  41. };
  42. exports.testCatchAndReturn = function(assert) {
  43. var wrapped = errors.catchAndReturn(function(x) {
  44. if (x == 1)
  45. return "one";
  46. if (x == 2)
  47. throw new Error("two");
  48. return this + x;
  49. });
  50. assert.equal(wrapped(1).returnValue, "one",
  51. "arg should be passed; return value should be returned");
  52. assert.ok(wrapped(2).exception, "exception should be returned");
  53. assert.equal(wrapped(2).exception.message, "two", "message is correct");
  54. assert.ok(wrapped(2).exception.fileName.indexOf("test-errors.js") != -1,
  55. "filename is present");
  56. assert.ok(wrapped(2).exception.stack, "stack is available");
  57. assert.equal(wrapped.call("hi", 3).returnValue, "hi3",
  58. "`this` should be set correctly");
  59. };
  60. require("sdk/test").run(exports);