Home Reference Source Test

spec/predicates/and.spec.ts

  1. import 'mocha';
  2.  
  3. import { given } from 'mocha-testdata';
  4. import sinon = require('sinon');
  5.  
  6. import { and, ensure, isDefined, isGreaterThan, isInteger, isLessThan, Predicate, TinyType } from '../../src';
  7. import { expect } from '../expect';
  8.  
  9. describe('predicates', () => {
  10.  
  11. /** @test {and} */
  12. describe('::and', () => {
  13.  
  14. class InvestmentLengthInYears extends TinyType {
  15. constructor(public readonly value: number) {
  16. super();
  17. ensure('InvestmentLengthInYears', value, and(
  18. isDefined(),
  19. isInteger(),
  20. isGreaterThan(0),
  21. isLessThan(50),
  22. ));
  23. }
  24. }
  25.  
  26. it('ensures that all the predicates are met', () => {
  27. expect(() => new InvestmentLengthInYears(10)).to.not.throw();
  28. });
  29.  
  30. given(
  31. [ null, 'InvestmentLengthInYears should be defined' ],
  32. [ 0.2, 'InvestmentLengthInYears should be an integer' ],
  33. [ -2, 'InvestmentLengthInYears should be greater than 0' ],
  34. [ 52, 'InvestmentLengthInYears should be less than 50' ],
  35. ).
  36. it('complains upon the first unmet predicate', (value: any, errorMessage: string) => {
  37. expect(() => new InvestmentLengthInYears(value))
  38. .to.throw(errorMessage);
  39. });
  40.  
  41. it('complains if there are no predicates specified', () => {
  42. expect(() => and()).to.throw(`Looks like you haven't specified any predicates to check the value against?`);
  43. });
  44.  
  45. it('stops evaluating the predicates upon the first failure', () => {
  46. const predicateEvaluated = sinon.spy();
  47. const predicateReturning = (result: boolean) => Predicate.to(result ? 'pass' : 'fail', (value: any) => {
  48. predicateEvaluated();
  49. return result;
  50. });
  51.  
  52. expect(() => ensure('value', null, and(
  53. predicateReturning(true),
  54. predicateReturning(false),
  55. predicateReturning(true),
  56. ))).to.throw('value should fail');
  57.  
  58. expect(predicateEvaluated.callCount).to.equal(2);
  59. });
  60. });
  61. });