error.test.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { expect, test } from 'vitest';
  2. import {
  3. CODAMA_ERROR__UNEXPECTED_NODE_KIND,
  4. CODAMA_ERROR__UNRECOGNIZED_NODE_KIND,
  5. CodamaError,
  6. isCodamaError,
  7. } from '../src';
  8. test('it exposes the Codama error context', () => {
  9. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { kind: 'missingNode' });
  10. expect(error.context.kind).toBe('missingNode');
  11. });
  12. test('it exposes the Codama error code', () => {
  13. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { kind: 'missingNode' });
  14. expect(error.context.__code).toBe(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND);
  15. });
  16. test('it calls the message formatter with the code and context', () => {
  17. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { kind: 'missingNode' });
  18. expect(error.message).toBe('Unrecognized node kind [missingNode].');
  19. });
  20. test('it exposes no cause when none is provided', () => {
  21. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { kind: 'missingNode' });
  22. expect(error.cause).toBeUndefined();
  23. });
  24. test('it exposes the cause when provided', () => {
  25. const cause = {} as unknown;
  26. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { cause, kind: 'missingNode' });
  27. expect(error.cause).toBe(cause);
  28. });
  29. test('it returns `true` for an instance of `CodamaError`', () => {
  30. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { kind: 'missingNode' });
  31. expect(isCodamaError(error)).toBe(true);
  32. });
  33. test('it returns `false` for an instance of `Error`', () => {
  34. expect(isCodamaError(new Error('bad thing'))).toBe(false);
  35. });
  36. test('it returns `true` when the error code matches', () => {
  37. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { kind: 'missingNode' });
  38. expect(isCodamaError(error, CODAMA_ERROR__UNRECOGNIZED_NODE_KIND)).toBe(true);
  39. });
  40. test('it returns `false` when the error code does not match', () => {
  41. const error = new CodamaError(CODAMA_ERROR__UNRECOGNIZED_NODE_KIND, { kind: 'missingNode' });
  42. expect(isCodamaError(error, CODAMA_ERROR__UNEXPECTED_NODE_KIND)).toBe(false);
  43. });