Home Reference Source Test

spec/predicates/property.spec.ts

  1. import 'mocha';
  2.  
  3. import { given } from 'mocha-testdata';
  4.  
  5. import { ensure, isDefined, isGreaterThanOrEqualTo, isString, property, TinyType } from '../../src';
  6. import { expect } from '../expect';
  7.  
  8. describe('predicates', () => {
  9.  
  10. /** @test {property} */
  11. describe('::property', () => {
  12.  
  13. /** @test {property} */
  14. describe('shifts the focus from the value itself to its property', () => {
  15.  
  16. class Name extends TinyType {
  17. constructor(public readonly value: string) {
  18. super();
  19. ensure('Name', value,
  20. isDefined(),
  21. property('length', isDefined(), isGreaterThanOrEqualTo(3)),
  22. isString(),
  23. );
  24. }
  25. }
  26.  
  27. /** @test {property} */
  28. it('ensures that the property meets the predicates', () => {
  29. expect(() => new Name('Jan')).to.not.throw();
  30. });
  31.  
  32. given(
  33. undefined,
  34. null,
  35. ).
  36. it('complains when the value is undefined', (value: any) => {
  37. expect(() => new Name({ length: value } as any)).
  38. to.throw(`Name should have a property "length" that is defined`);
  39. });
  40.  
  41. given<any, string>(
  42. [undefined, 'Name should be defined'],
  43. [{ length: undefined }, 'Name should have a property "length" that is defined'],
  44. ['JM', 'Name should have a property "length" that is either equal to 3 or is greater than 3'],
  45. [['J', 'a', 'n'], 'Name should be a string'],
  46. ).
  47. it('can be composed with other predicates', (value: any, expectedError: string) => {
  48. expect(() => new Name(value)).
  49. to.throw(expectedError);
  50. });
  51. });
  52. });
  53. });