test-common.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. }