test-require.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 traceback = require('sdk/console/traceback');
  6. const REQUIRE_LINE_NO = 30;
  7. exports.test_no_args = function(assert) {
  8. let passed = tryRequireModule(assert);
  9. assert.ok(passed, 'require() with no args should raise helpful error');
  10. };
  11. exports.test_invalid_sdk_module = function (assert) {
  12. let passed = tryRequireModule(assert, 'sdk/does-not-exist');
  13. assert.ok(passed, 'require() with an invalid sdk module should raise');
  14. };
  15. exports.test_invalid_relative_module = function (assert) {
  16. let passed = tryRequireModule(assert, './does-not-exist');
  17. assert.ok(passed, 'require() with an invalid relative module should raise');
  18. };
  19. function tryRequireModule(assert, module) {
  20. let passed = false;
  21. try {
  22. // This line number is important, referenced in REQUIRE_LINE_NO
  23. let doesNotExist = require(module);
  24. } catch(e) {
  25. checkError(assert, module, e);
  26. passed = true;
  27. }
  28. return passed;
  29. }
  30. function checkError (assert, name, e) {
  31. let msg = e.toString();
  32. if (name) {
  33. assert.ok(/is not found at/.test(msg),
  34. 'Error message indicates module not found');
  35. assert.ok(msg.indexOf(name.replace(/\./g,'')) > -1,
  36. 'Error message has the invalid module name in the message');
  37. }
  38. else {
  39. assert.equal(msg.indexOf('Error: you must provide a module name when calling require() from '), 0);
  40. assert.ok(msg.indexOf("test-require") !== -1, msg);
  41. }
  42. // we'd also like to assert that the right filename
  43. // and linenumber is in the stacktrace
  44. let tb = traceback.fromException(e);
  45. // Get the second to last frame, as the last frame is inside
  46. // toolkit/loader
  47. let lastFrame = tb[tb.length-2];
  48. assert.ok(lastFrame.fileName.indexOf("test-require.js") !== -1,
  49. 'Filename found in stacktrace');
  50. assert.equal(lastFrame.lineNumber, REQUIRE_LINE_NO,
  51. 'stacktrace has correct line number');
  52. }
  53. require('test').run(exports);