test-common.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Custom error for failed assertions.
  3. * @constructor
  4. * @param {string} message Error message
  5. * @returns Error
  6. */
  7. function AssertionError(message) {
  8. var instance = new Error(message);
  9. instance.name = 'AssertionError';
  10. Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
  11. return instance;
  12. }
  13. /**
  14. * Throws an `AssertionError` if `value` is not truthy.
  15. * @param {*} value Value to be tested
  16. */
  17. function assert(value) {
  18. if (!value)
  19. throw new AssertionError("The assertion failed!");
  20. }
  21. /**
  22. * Throws an `AssertionError` when called.
  23. * @throws {AssertionError}
  24. */
  25. function assertNotReached() {
  26. throw new AssertionError("assertNotReached() was reached!");
  27. }
  28. /**
  29. * Ensures the provided functions throws a specific error.
  30. * @param {Function} testFunction Function executing the throwing code
  31. * @param {object} [options]
  32. * @param {Error} [options.error] Expected error type
  33. * @param {string} [options.name] Expected error name
  34. * @param {string} [options.message] Expected error message
  35. */
  36. function assertThrowsError(testFunction, options) {
  37. try {
  38. testFunction();
  39. assertNotReached();
  40. } catch (e) {
  41. if (options.error !== undefined)
  42. assert(e instanceof options.error);
  43. if (options.name !== undefined)
  44. assert(e.name === options.name);
  45. if (options.message !== undefined)
  46. assert(e.message === options.message);
  47. }
  48. }
  49. /**
  50. * Check whether the difference between two numbers is less than 0.000001.
  51. * @param {Number} a First number
  52. * @param {Number} b Second number
  53. */
  54. function isClose(a, b) {
  55. return Math.abs(a - b) < 0.000001;
  56. }