UNPKG

@geekbears/gb-class-validators

Version:

Geekbears custom validators using class-validator package.

101 lines (84 loc) 3.57 kB
import { Validator } from 'class-validator'; import { IsGBPhoneNumber } from '../validators'; class TestClass { @IsGBPhoneNumber({ dev: ['US'], prod: ['US'] }) phone: any; // Type is any to mimmick JSON requests behavior } describe('Phone Validator', () => { let validator: Validator; beforeEach(() => { validator = new Validator(); }); describe('Env different from production', () => { test('should fail when not a string', async () => { const model = new TestClass(); model.phone = 98234; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should fail when not providing an international code', async () => { const model = new TestClass(); model.phone = '2025550115'; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should fail when providing an invalid phone number', async () => { const model = new TestClass(); model.phone = '98234'; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should fail when providing a number from an invalid region', async () => { const model = new TestClass(); model.phone = '+525522626391'; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should pass when providing a valid phone number', async () => { const model = new TestClass(); model.phone = '+12025550115'; const errors = await validator.validate(model); expect(errors.length).toEqual(0); }); }); describe('Prod env', () => { const ENV = process.env; beforeEach(() => { jest.resetModules(); process.env = { ...ENV, NODE_ENV: 'production' }; }); afterEach(() => { process.env = ENV; }); test('should fail when not a string', async () => { const model = new TestClass(); model.phone = 98234; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should fail when not providing an international code', async () => { const model = new TestClass(); model.phone = '2025550115'; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should fail when providing an invalid phone number', async () => { const model = new TestClass(); model.phone = '98234'; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should fail when providing a number from an invalid region', async () => { const model = new TestClass(); model.phone = '+525522626391'; const errors = await validator.validate(model); expect(errors.length).toBeGreaterThan(0); }); test('should pass when providing a valid phone number', async () => { const model = new TestClass(); model.phone = '+12025550115'; const errors = await validator.validate(model); expect(errors.length).toEqual(0); }); }); });