How to use validateProps method in Playwright Internal

Best JavaScript code snippet using playwright-internal

index.test.js

Source:index.test.js Github

copy

Full Screen

...45 }46}47const prefix = `PropTypes`48describe(`prop-validator package`, () => {49 describe(`validateProps()`, () => {50 it(`correctly validates basic types`, () => {51 const valid = [52 validateProps({53 a: PropTypes.string,54 b: PropTypes.number,55 c: PropTypes.integer,56 d: PropTypes.boolean,57 e: PropTypes.function,58 f: PropTypes.object,59 g: PropTypes.array,60 h: PropTypes.symbol,61 i: PropTypes.regex,62 j: PropTypes.any63 }, {64 a: 'hello',65 b: 123.123,66 c: 10,67 d: false,68 e: () => { console.log('hi'); },69 f: { a: 'b' },70 g: ['a', 'b', 'c'],71 h: Symbol('hello world'),72 i: /[0-9]+/g,73 j: 'whatever'74 }),75 validateProps({76 q: PropTypes.numberRange(-1.2, 5),77 w: PropTypes.integerRange(-1.2, 5),78 e: PropTypes.stringMatching(/a|b/),79 r: PropTypes.oneOf(['qwerty', 'azerty']),80 t: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),81 y: PropTypes.arrayOf(PropTypes.string),82 u: PropTypes.objectOf(PropTypes.number),83 i: PropTypes.instanceOf(TestClassA),84 o: PropTypes.customProp((value, key, object, state, parentInfo) => typeof value === 'string' || value === 5, 'Any string or number 5'),85 p: PropTypes.shape({86 a: PropTypes.string,87 b: PropTypes.number88 }),89 a: PropTypes.exact({90 a: PropTypes.string,91 b: PropTypes.number92 })93 }, {94 q: 2.2,95 w: 2,96 e: 'a',97 r: 'qwerty',98 t: 5,99 y: ['a', 'b', 'c'],100 u: { a: 4, b: 5 },101 i: new TestClassA(),102 o: 5,103 p: {104 a: 'a',105 b: 5,106 c: 'anything'107 },108 a: {109 a: 'a',110 b: 5111 }112 })113 ]114 const invalid = [115 validateProps({116 a: PropTypes.string,117 b: PropTypes.number,118 c: PropTypes.integer,119 d: PropTypes.boolean,120 e: PropTypes.function,121 f: PropTypes.object,122 g: PropTypes.array,123 h: PropTypes.symbol,124 i: PropTypes.regex,125 j: PropTypes.any.isRequired126 }, {127 a: 4,128 b: 'a',129 c: 23.34,130 d: [],131 e: {},132 f: () => true,133 g: Symbol('nah'),134 h: /[0-9]+/,135 i: new TestClassA(),136 j: undefined137 })138 ]139 for (const validItem of valid) {140 expect(validItem).toMatchObject(validTypeCheck())141 }142 for (const invalidItem of invalid) {143 expect(invalidItem).toMatchObject(invalidTypeCheck())144 }145 const invalidProps1 = validateProps({ a: PropTypes.string, b: PropTypes.number, c: PropTypes.integer }, { a: 'hello', b: 10, c: 10.50 })146 expect(invalidProps1).toMatchObject(invalidTypeCheck())147 expect(invalidProps1.errors).toHaveLength(1)148 expect(invalidProps1.results).toHaveLength(3)149 const invalidProps2 = validateProps({ a: PropTypes.string, b: PropTypes.number, c: PropTypes.integer.isRequired }, { a: 'hello', b: 10 })150 expect(invalidProps2).toMatchObject(invalidTypeCheck())151 expect(invalidProps2.errors).toHaveLength(1)152 expect(invalidProps2.results).toHaveLength(3)153 const validProps1 = validateProps({154 a: PropTypes.string,155 b: PropTypes.shape({156 a: PropTypes.string,157 b: PropTypes.shape({158 a: PropTypes.shape({159 a: PropTypes.number,160 b: PropTypes.string161 }),162 b: PropTypes.arrayOf(PropTypes.shape({163 a: PropTypes.string,164 b: PropTypes.number,165 c: PropTypes.stringMatching(/a|b/)166 }))167 })168 })169 }, {170 a: 'aaa',171 b: {172 a: 'aaa',173 b: {174 a: {175 a: 234,176 b: 'bbb'177 },178 b: [179 { a: 'aaa', b: 3, c: 'a' },180 { a: 'aa', b: 4, c: 'a' },181 { a: 'a', b: 5, c: 'b' },182 { a: 'aa', b: 76, c: 'a' },183 { a: 'aaa', b: 77, c: 'b' }184 ]185 }186 }187 })188 expect(validProps1).toMatchObject(validTypeCheck())189 expect(validProps1.results).toHaveLength(23)190 expect(validProps1.results[0].objectPath).toBe('a')191 expect(validProps1.results[1].objectPath).toBe('b')192 expect(validProps1.results[2].objectPath).toBe('b.a')193 expect(validProps1.results[3].objectPath).toBe('b.b')194 expect(validProps1.results[4].objectPath).toBe('b.b.a')195 expect(validProps1.results[5].objectPath).toBe('b.b.a.a')196 expect(validProps1.results[6].objectPath).toBe('b.b.a.b')197 expect(validProps1.results[7].objectPath).toBe('b.b.b')198 expect(validProps1.results[8].objectPath).toBe('b.b.b[0].a')199 expect(validProps1.results[9].objectPath).toBe('b.b.b[0].b')200 expect(validProps1.results[10].objectPath).toBe('b.b.b[0].c')201 expect(validProps1.results[11].objectPath).toBe('b.b.b[1].a')202 expect(validProps1.results[12].objectPath).toBe('b.b.b[1].b')203 expect(validProps1.results[13].objectPath).toBe('b.b.b[1].c')204 expect(validProps1.results[14].objectPath).toBe('b.b.b[2].a')205 expect(validProps1.results[15].objectPath).toBe('b.b.b[2].b')206 expect(validProps1.results[16].objectPath).toBe('b.b.b[2].c')207 expect(validProps1.results[17].objectPath).toBe('b.b.b[3].a')208 expect(validProps1.results[18].objectPath).toBe('b.b.b[3].b')209 expect(validProps1.results[19].objectPath).toBe('b.b.b[3].c')210 expect(validProps1.results[20].objectPath).toBe('b.b.b[4].a')211 expect(validProps1.results[21].objectPath).toBe('b.b.b[4].b')212 expect(validProps1.results[22].objectPath).toBe('b.b.b[4].c')213 })214 })215 describe(`PropTypes`, () => {216 it(`${prefix}.string`, () => {217 const valid1 = validateProps({ val: PropTypes.string }, { val: 'hello' })218 const valid2 = validateProps({ val: PropTypes.string }, { val: null })219 const valid3 = validateProps({ val: PropTypes.string.isRequired }, { val: 'hello' })220 const invalid1 = validateProps({ val: PropTypes.string }, { val: 5 })221 const invalid2 = validateProps({ val: PropTypes.string.isRequired }, { val: null })222 expect(valid1).toMatchObject(validTypeCheck())223 expect(valid2).toMatchObject(validTypeCheck())224 expect(valid1.results[0]).toMatchObject(validResult('val', ['string', 'null']))225 expect(valid2.results[0]).toMatchObject(validResult('val', ['string', 'null']))226 expect(valid3.results[0]).toMatchObject(validResult('val', ['string']))227 expect(invalid1).toMatchObject(invalidTypeCheck())228 expect(invalid2).toMatchObject(invalidTypeCheck())229 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['string', 'null'], { message: `Property 'val' should be type 'string | null', but type 'number' was found` }))230 expect(invalid2.results[0]).toMatchObject(invalidResult('val', ['string'], { message: `Property 'val' should be type 'string', but type 'null' was found` }))231 })232 it(`${prefix}.number`, () => {233 const valid1 = validateProps({ val: PropTypes.number }, { val: 5.5 })234 const valid2 = validateProps({ val: PropTypes.number }, { val: 6 })235 const valid3 = validateProps({ val: PropTypes.number }, { val: -5 })236 const valid4 = validateProps({ val: PropTypes.number.isRequired }, { val: -5 })237 238 const invalid1 = validateProps({ val: PropTypes.number }, { val: 'a' })239 const invalid2 = validateProps({ val: PropTypes.number }, { val: [] })240 const invalid3 = validateProps({ val: PropTypes.number }, { val: {} })241 const invalid4 = validateProps({ val: PropTypes.number.isRequired }, { val: null })242 expect(valid1).toMatchObject(validTypeCheck())243 expect(valid2).toMatchObject(validTypeCheck())244 expect(valid3).toMatchObject(validTypeCheck())245 expect(valid4).toMatchObject(validTypeCheck())246 expect(valid1.results[0]).toMatchObject(validResult('val', ['number', 'null']))247 expect(valid2.results[0]).toMatchObject(validResult('val', ['number', 'null']))248 expect(valid3.results[0]).toMatchObject(validResult('val', ['number', 'null']))249 expect(valid4.results[0]).toMatchObject(validResult('val', ['number']))250 expect(invalid1).toMatchObject(invalidTypeCheck())251 expect(invalid2).toMatchObject(invalidTypeCheck())252 expect(invalid3).toMatchObject(invalidTypeCheck())253 expect(invalid4).toMatchObject(invalidTypeCheck())254 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['number', 'null'], { message: `Property 'val' should be type 'number | null', but type 'string' was found` }))255 expect(invalid2.results[0]).toMatchObject(invalidResult('val', ['number', 'null'], { message: `Property 'val' should be type 'number | null', but type 'Array' was found` }))256 expect(invalid3.results[0]).toMatchObject(invalidResult('val', ['number', 'null'], { message: `Property 'val' should be type 'number | null', but type 'Object' was found` }))257 expect(invalid4.results[0]).toMatchObject(invalidResult('val', ['number'], { message: `Property 'val' should be type 'number', but type 'null' was found` }))258 })259 it(`${prefix}.integer`, () => {260 const valid1 = validateProps({ val: PropTypes.integer }, { val: 2 })261 const valid2 = validateProps({ val: PropTypes.integer }, { val: 6 })262 const valid3 = validateProps({ val: PropTypes.integer.isRequired }, { val: 6 })263 const invalid1 = validateProps({ val: PropTypes.integer }, { val: 2.5 })264 const invalid2 = validateProps({ val: PropTypes.integer }, { val: 'a' })265 const invalid3 = validateProps({ val: PropTypes.integer.isRequired }, { val: null })266 expect(valid1).toMatchObject(validTypeCheck())267 expect(valid2).toMatchObject(validTypeCheck())268 expect(valid3).toMatchObject(validTypeCheck())269 expect(valid1.results[0]).toMatchObject(validResult('val', ['number: integer', 'null']))270 expect(valid2.results[0]).toMatchObject(validResult('val', ['number: integer', 'null']))271 expect(valid3.results[0]).toMatchObject(validResult('val', ['number: integer']))272 expect(invalid1).toMatchObject(invalidTypeCheck())273 expect(invalid2).toMatchObject(invalidTypeCheck())274 expect(invalid3).toMatchObject(invalidTypeCheck())275 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['number: integer', 'null'], { message: `Property 'val' should be type 'number: integer | null'` }))276 expect(invalid2.results[0]).toMatchObject(invalidResult('val', ['number: integer', 'null'], { message: `Property 'val' should be type 'number: integer | null', but type 'string' was found` }))277 expect(invalid3.results[0]).toMatchObject(invalidResult('val', ['number: integer'], { message: `Property 'val' should be type 'number: integer', but type 'null' was found` }))278 })279 it(`${prefix}.boolean`, () => {280 const valid1 = validateProps({ val: PropTypes.boolean }, { val: true })281 const valid2 = validateProps({ val: PropTypes.boolean }, { val: false })282 const valid3 = validateProps({ val: PropTypes.bool }, { val: true })283 const valid4 = validateProps({ val: PropTypes.bool }, { val: false })284 const valid5 = validateProps({ val: PropTypes.bool }, { val: null })285 const valid6 = validateProps({ val: PropTypes.bool.isRequired }, { val: false })286 const invalid1 = validateProps({ val: PropTypes.boolean }, { val: 2.5 })287 const invalid2 = validateProps({ val: PropTypes.boolean }, { val: 'a' })288 const invalid3 = validateProps({ val: PropTypes.boolean.isRequired }, { val: null })289 const invalid4 = validateProps({ val: PropTypes.bool.isRequired }, { val: null })290 const invalid5 = validateProps({ val: PropTypes.bool.isRequired }, { val: undefined })291 expect(valid1).toMatchObject(validTypeCheck())292 expect(valid2).toMatchObject(validTypeCheck())293 expect(valid3).toMatchObject(valid1)294 expect(valid4).toMatchObject(valid2)295 expect(valid5).toMatchObject(validTypeCheck())296 expect(valid6).toMatchObject(validTypeCheck())297 expect(valid1.results[0]).toMatchObject(validResult('val', ['boolean', 'null']))298 expect(valid2.results[0]).toMatchObject(validResult('val', ['boolean', 'null']))299 expect(valid3.results[0]).toMatchObject(validResult('val', ['boolean', 'null']))300 expect(valid4.results[0]).toMatchObject(validResult('val', ['boolean', 'null']))301 expect(valid5.results[0]).toMatchObject(validResult('val', ['boolean', 'null']))302 expect(valid6.results[0]).toMatchObject(validResult('val', ['boolean']))303 expect(invalid1).toMatchObject(invalidTypeCheck())304 expect(invalid2).toMatchObject(invalidTypeCheck())305 expect(invalid3).toMatchObject(invalidTypeCheck())306 expect(invalid4).toMatchObject(invalidTypeCheck())307 expect(invalid5).toMatchObject(invalidTypeCheck())308 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['boolean', 'null'], { message: `Property 'val' should be type 'boolean | null', but type 'number' was found` }))309 expect(invalid2.results[0]).toMatchObject(invalidResult('val', ['boolean', 'null'], { message: `Property 'val' should be type 'boolean | null', but type 'string' was found` }))310 expect(invalid3.results[0]).toMatchObject(invalidResult('val', ['boolean'], { message: `Property 'val' should be type 'boolean', but type 'null' was found` }))311 expect(invalid4.results[0]).toMatchObject(invalidResult('val', ['boolean'], { message: `Property 'val' should be type 'boolean', but type 'null' was found` }))312 expect(invalid5.results[0]).toMatchObject(invalidResult('val', ['boolean'], { message: `Property 'val' should be type 'boolean', but type 'undefined' was found` }))313 })314 it(`${prefix}.function`, () => {315 const testFn = () => console.log('hi')316 const valid1 = validateProps({ val: PropTypes.function }, { val: testFn })317 const valid2 = validateProps({ val: PropTypes.function }, { val: function something() { console.log('hi'); } })318 const valid3 = validateProps({ val: PropTypes.function }, { val: function () { console.log('hi'); } })319 const valid4 = validateProps({ val: PropTypes.function }, { val: async () => { console.log('hi'); } })320 const valid5 = validateProps({ val: PropTypes.function }, { val: async function () { console.log('hi'); } })321 const valid6 = validateProps({ val: PropTypes.func }, { val: testFn })322 const valid7 = validateProps({ val: PropTypes.func.isRequired }, { val: testFn })323 const invalid1 = validateProps({ val: PropTypes.function }, { val: [] })324 const invalid2 = validateProps({ val: PropTypes.function }, { val: 'a' })325 const invalid3 = validateProps({ val: PropTypes.function.isRequired }, { val: null })326 expect(valid1).toMatchObject(validTypeCheck())327 expect(valid2).toMatchObject(validTypeCheck())328 expect(valid3).toMatchObject(validTypeCheck())329 expect(valid4).toMatchObject(validTypeCheck())330 expect(valid5).toMatchObject(validTypeCheck())331 expect(valid6).toMatchObject(valid1)332 expect(valid6).toMatchObject(validTypeCheck())333 expect(valid1.results[0]).toMatchObject(validResult('val', ['function', 'null']))334 expect(valid2.results[0]).toMatchObject(validResult('val', ['function', 'null']))335 expect(valid3.results[0]).toMatchObject(validResult('val', ['function', 'null']))336 expect(valid4.results[0]).toMatchObject(validResult('val', ['function', 'null']))337 expect(valid5.results[0]).toMatchObject(validResult('val', ['function', 'null']))338 expect(valid6.results[0]).toMatchObject(validResult('val', ['function', 'null']))339 expect(valid7.results[0]).toMatchObject(validResult('val', ['function']))340 341 expect(invalid1).toMatchObject(invalidTypeCheck())342 expect(invalid2).toMatchObject(invalidTypeCheck())343 expect(invalid3).toMatchObject(invalidTypeCheck())344 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['function', 'null'], { message: `Property 'val' should be type 'function | null', but type 'Array' was found` }))345 expect(invalid2.results[0]).toMatchObject(invalidResult('val', ['function', 'null'], { message: `Property 'val' should be type 'function | null', but type 'string' was found` }))346 expect(invalid3.results[0]).toMatchObject(invalidResult('val', ['function'], { message: `Property 'val' should be type 'function', but type 'null' was found` }))347 })348 it(`${prefix}.object`, () => {349 const valid1 = validateProps({ val: PropTypes.object }, { val: {} })350 const valid2 = validateProps({ val: PropTypes.object }, { val: { a: 'b' } })351 const valid3 = validateProps({ val: PropTypes.object.isRequired }, { val: new Object() })352 const invalid1 = validateProps({ val: PropTypes.object }, { val: [] })353 expect(valid1).toMatchObject(validTypeCheck())354 expect(valid2).toMatchObject(validTypeCheck())355 expect(valid3).toMatchObject(validTypeCheck())356 expect(valid1.results[0]).toMatchObject(validResult('val', ['Object<*>', 'null']))357 expect(valid2.results[0]).toMatchObject(validResult('val', ['Object<*>', 'null']))358 expect(valid3.results[0]).toMatchObject(validResult('val', ['Object<*>']))359 360 expect(invalid1).toMatchObject(invalidTypeCheck())361 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['Object<*>', 'null'], { message: `Property 'val' should be type 'Object<*> | null', but type 'Array' was found` }))362 })363 it(`${prefix}.array`, () => {364 const valid1 = validateProps({ val: PropTypes.array }, { val: ['a', 'b'] })365 const valid2 = validateProps({ val: PropTypes.array.isRequired }, { val: new Array() })366 const invalid1 = validateProps({ val: PropTypes.array }, { val: 5.5 })367 const invalid2 = validateProps({ val: PropTypes.array.isRequired }, { val: null })368 expect(valid1).toMatchObject(validTypeCheck())369 expect(valid2).toMatchObject(validTypeCheck())370 expect(valid1.results[0]).toMatchObject(validResult('val', ['Array<*>', 'null']))371 expect(valid2.results[0]).toMatchObject(validResult('val', ['Array<*>']))372 373 expect(invalid1).toMatchObject(invalidTypeCheck())374 expect(invalid2).toMatchObject(invalidTypeCheck())375 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['Array<*>', 'null'], { message: `Property 'val' should be type 'Array<*> | null', but type 'number' was found` }))376 expect(invalid2.results[0]).toMatchObject(invalidResult('val', ['Array<*>'], { message: `Property 'val' should be type 'Array<*>', but type 'null' was found` }))377 })378 it(`${prefix}.symbol`, () => {379 const valid1 = validateProps({ val: PropTypes.symbol.isRequired }, { val: Symbol('a') })380 const invalid1 = validateProps({ val: PropTypes.symbol.isRequired }, { val: 5.5 })381 expect(valid1).toMatchObject(validTypeCheck())382 expect(valid1.results[0]).toMatchObject(validResult('val', ['symbol']))383 384 expect(invalid1).toMatchObject(invalidTypeCheck())385 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['symbol'], { message: `Property 'val' should be type 'symbol', but type 'number' was found` }))386 })387 it(`${prefix}.regex`, () => {388 const valid1 = validateProps({ val: PropTypes.regex.isRequired }, { val: /a|b/ })389 const valid2 = validateProps({ val: PropTypes.regex.isRequired }, { val: /((.+?)[0-9]{2})/g })390 const valid3 = validateProps({ val: PropTypes.regex.isRequired }, { val: new RegExp('^([0-9]|b|c)+$', 'i') })391 const invalid1 = validateProps({ val: PropTypes.regex.isRequired }, { val: 5.5 })392 expect(valid1).toMatchObject(validTypeCheck())393 expect(valid1.results[0]).toMatchObject(validResult('val', ['RegExp']))394 expect(valid2).toMatchObject(validTypeCheck())395 expect(valid2.results[0]).toMatchObject(validResult('val', ['RegExp']))396 expect(valid3).toMatchObject(validTypeCheck())397 expect(valid3.results[0]).toMatchObject(validResult('val', ['RegExp']))398 399 expect(invalid1).toMatchObject(invalidTypeCheck())400 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['RegExp'], { message: `Property 'val' should be type 'RegExp', but type 'number' was found` }))401 })402 it(`${prefix}.error`, () => {403 class MyError extends Error {404 constructor(args) {405 super(args)406 this.code = 'hello world'407 }408 }409 const getError = fn => {410 try {411 return fn()412 }413 catch (err) {414 return err415 }416 }417 const valid = [418 validateProps({ val: PropTypes.error.isRequired }, { val: new Error('test') }),419 validateProps({ val: PropTypes.error.isRequired }, { val: new TypeError('test') }),420 validateProps({ val: PropTypes.error.isRequired }, { val: new ReferenceError('test') }),421 validateProps({ val: PropTypes.error.isRequired }, { val: new SyntaxError('test') }),422 validateProps({ val: PropTypes.error.isRequired }, { val: new TypeError('test') }),423 validateProps({ val: PropTypes.error.isRequired }, { val: new URIError('test') }),424 validateProps({ val: PropTypes.error.isRequired }, { val: new MyError('test') }),425 validateProps({ val: PropTypes.error.isRequired }, { val: getError(() => { a() }) })426 ]427 const invalid = [428 validateProps({ val: PropTypes.error.isRequired }, { val: 5.5 }),429 validateProps({ val: PropTypes.error.isRequired }, { val: getError(() => { 1 + 1; }) })430 ]431 for (const validItem of valid) {432 expect(validItem).toMatchObject(validTypeCheck())433 }434 for (const invalidItem of invalid) {435 expect(invalidItem).toMatchObject(invalidTypeCheck())436 }437 expect(invalid[0].results[0]).toMatchObject(invalidResult('val', ['Error'], { message: `Property 'val' should be type 'Error', but type 'number' was found` }))438 })439 it(`${prefix}.null`, () => {440 const valid = [441 validateProps({ val: PropTypes.null }, { val: null }),442 validateProps({ val: PropTypes.null.isRequired }, { val: null }),443 validateProps({ val: PropTypes.null }, { val: undefined })444 ]445 const invalid = [446 validateProps({ val: PropTypes.null }, { val: 1 }),447 validateProps({ val: PropTypes.null.isRequired }, { val: undefined }),448 validateProps({ val: PropTypes.null }, { val: 'b' })449 ]450 for (const validItem of valid) {451 expect(validItem).toMatchObject(validTypeCheck())452 }453 for (const invalidItem of invalid) {454 expect(invalidItem).toMatchObject(invalidTypeCheck())455 }456 expect(invalid[0].results[0]).toMatchObject(invalidResult('val', ['null'], { message: `Property 'val' should be type 'null', but type 'number' was found` }))457 })458 it(`${prefix}.undefined`, () => {459 const valid = [460 validateProps({ val: PropTypes.undefined }, { val: undefined }),461 validateProps({ val: PropTypes.undefined.isRequired }, { val: undefined })462 ]463 const invalid = [464 validateProps({ val: PropTypes.undefined }, { val: 1 }),465 validateProps({ val: PropTypes.undefined }, { val: null }),466 validateProps({ val: PropTypes.undefined.isRequired }, { val: null }),467 validateProps({ val: PropTypes.undefined }, { val: 'b' })468 ]469 for (const validItem of valid) {470 expect(validItem).toMatchObject(validTypeCheck())471 }472 for (const invalidItem of invalid) {473 expect(invalidItem).toMatchObject(invalidTypeCheck())474 }475 expect(invalid[0].results[0]).toMatchObject(invalidResult('val', ['undefined'], { message: `Property 'val' should be type 'undefined', but type 'number' was found` }))476 })477 it(`${prefix}.any`, () => {478 const valid = [479 validateProps({ val: PropTypes.any }, { val: 'a' }),480 validateProps({ val: PropTypes.any }, { val: 2 }),481 validateProps({ val: PropTypes.any }, { val: [] }),482 validateProps({ val: PropTypes.any }, { val: {} }),483 validateProps({ val: PropTypes.any }, { val: Symbol('a') }),484 validateProps({ val: PropTypes.any }, { val: /[a-z]/ }),485 validateProps({ val: PropTypes.any }, { val: () => { console.log('a'); } }),486 validateProps({ val: PropTypes.any }, { val: null }),487 validateProps({ val: PropTypes.any }, { val: undefined }),488 validateProps({ val: PropTypes.any.isRequired }, { val: null })489 ]490 const invalid1 = validateProps({ val: PropTypes.any.isRequired }, { val: undefined })491 for (const validItem of valid) {492 expect(validItem).toMatchObject(validTypeCheck())493 expect(validItem.results[0]).toMatchObject(validResult('val', ['*']))494 }495 496 expect(invalid1).toMatchObject(invalidTypeCheck())497 expect(invalid1.results[0]).toMatchObject(invalidResult('val', ['*'], { message: `Property 'val' should be type '*', but type 'undefined' was found` }))498 })499 it(`${prefix}.numberRange`, () => {500 const valid = [501 validateProps({ val: PropTypes.numberRange(0, 5) }, { val: 3.5 }),502 validateProps({ val: PropTypes.numberRange.inclusive(0, 5) }, { val: 3.5 }),503 validateProps({ val: PropTypes.numberRange.inclusive(0, 5) }, { val: 5 }),504 validateProps({ val: PropTypes.numberRange.exclusive(0, 5) }, { val: 4.5 }),505 validateProps({ val: PropTypes.numberRange.greaterThan(0) }, { val: 2.5 }),506 validateProps({ val: PropTypes.numberRange.greaterThanOrEqual(0) }, { val: 0 }),507 validateProps({ val: PropTypes.numberRange.lessThan(0) }, { val: -4.5 }),508 validateProps({ val: PropTypes.numberRange.lessThanOrEqual(0) }, { val: 0 })509 ]510 const invalid = [511 validateProps({ val: PropTypes.numberRange(0, 5) }, { val: -5 }),512 validateProps({ val: PropTypes.numberRange.inclusive(0, 5) }, { val: -5 }),513 validateProps({ val: PropTypes.numberRange.exclusive(0, 5) }, { val: 9 }),514 validateProps({ val: PropTypes.numberRange.exclusive(0, 5) }, { val: 5 }),515 validateProps({ val: PropTypes.numberRange.greaterThan(0) }, { val: -2.5 }),516 validateProps({ val: PropTypes.numberRange.greaterThan(0) }, { val: 0 }),517 validateProps({ val: PropTypes.numberRange.greaterThanOrEqual(0) }, { val: -5 }),518 validateProps({ val: PropTypes.numberRange.lessThan(0) }, { val: 4.5 }),519 validateProps({ val: PropTypes.numberRange.lessThan(0) }, { val: 0 }),520 validateProps({ val: PropTypes.numberRange.lessThanOrEqual(0) }, { val: 2 })521 ]522 for (const validItem of valid) {523 expect(validItem).toMatchObject(validTypeCheck())524 }525 for (const invalidItem of invalid) {526 expect(invalidItem).toMatchObject(invalidTypeCheck())527 }528 expect(() => validateProps({ val: PropTypes.numberRange() }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)529 expect(() => validateProps({ val: PropTypes.numberRange(0) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)530 expect(() => validateProps({ val: PropTypes.numberRange(1, 2, 3) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)531 expect(() => validateProps({ val: PropTypes.numberRange.inclusive() }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)532 expect(() => validateProps({ val: PropTypes.numberRange.inclusive(0) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)533 expect(() => validateProps({ val: PropTypes.numberRange.inclusive(0, 1, 2) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)534 expect(() => validateProps({ val: PropTypes.numberRange.exclusive() }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)535 expect(() => validateProps({ val: PropTypes.numberRange.exclusive(0) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)536 expect(() => validateProps({ val: PropTypes.numberRange.exclusive(0, 1, 2) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)537 expect(() => validateProps({ val: PropTypes.numberRange.greaterThan() }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)538 expect(() => validateProps({ val: PropTypes.numberRange.greaterThan(0, 1) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)539 expect(() => validateProps({ val: PropTypes.numberRange.greaterThan(0, 1, 2, 3) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)540 expect(() => validateProps({ val: PropTypes.numberRange.greaterThanOrEqual() }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)541 expect(() => validateProps({ val: PropTypes.numberRange.greaterThanOrEqual(0, 1) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)542 expect(() => validateProps({ val: PropTypes.numberRange.greaterThanOrEqual(0, 1, 2, 3) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)543 expect(() => validateProps({ val: PropTypes.numberRange.lessThan() }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)544 expect(() => validateProps({ val: PropTypes.numberRange.lessThan(0, 1) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)545 expect(() => validateProps({ val: PropTypes.numberRange.lessThan(0, 1, 2, 3) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)546 expect(() => validateProps({ val: PropTypes.numberRange.lessThanOrEqual() }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)547 expect(() => validateProps({ val: PropTypes.numberRange.lessThanOrEqual(0, 1) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)548 expect(() => validateProps({ val: PropTypes.numberRange.lessThanOrEqual(0, 1, 2, 3) }, { val: 3.5 })).toThrow(PropTypesValidatorErrorBase)549 })550 it(`${prefix}.integerRange`, () => {551 const valid = [552 validateProps({ val: PropTypes.integerRange(0, 5) }, { val: 3 }),553 validateProps({ val: PropTypes.integerRange.inclusive(0, 5) }, { val: 3 }),554 validateProps({ val: PropTypes.integerRange.inclusive(0, 5) }, { val: 5 }),555 validateProps({ val: PropTypes.integerRange.exclusive(0, 5) }, { val: 4 }),556 validateProps({ val: PropTypes.integerRange.greaterThan(0) }, { val: 2 }),557 validateProps({ val: PropTypes.integerRange.greaterThanOrEqual(0) }, { val: 0 }),558 validateProps({ val: PropTypes.integerRange.lessThan(0) }, { val: -4 }),559 validateProps({ val: PropTypes.integerRange.lessThanOrEqual(0) }, { val: 0 })560 ]561 const validRangeButNonIntegers = [562 validateProps({ val: PropTypes.integerRange(0, 5) }, { val: 3.5 }),563 validateProps({ val: PropTypes.integerRange.inclusive(0, 5) }, { val: 3.5 }),564 validateProps({ val: PropTypes.integerRange.inclusive(0, 5) }, { val: 4.5 }),565 validateProps({ val: PropTypes.integerRange.exclusive(0, 5) }, { val: 4.5 }),566 validateProps({ val: PropTypes.integerRange.greaterThan(0) }, { val: 2.5 }),567 validateProps({ val: PropTypes.integerRange.greaterThanOrEqual(0) }, { val: 0.5 }),568 validateProps({ val: PropTypes.integerRange.lessThan(0) }, { val: -4.5 }),569 validateProps({ val: PropTypes.integerRange.lessThanOrEqual(0) }, { val: -0.5 })570 ]571 const invalid = [572 validateProps({ val: PropTypes.integerRange(0, 5) }, { val: -5 }),573 validateProps({ val: PropTypes.integerRange.inclusive(0, 5) }, { val: -5 }),574 validateProps({ val: PropTypes.integerRange.exclusive(0, 5) }, { val: 9 }),575 validateProps({ val: PropTypes.integerRange.exclusive(0, 5) }, { val: 5 }),576 validateProps({ val: PropTypes.integerRange.greaterThan(0) }, { val: -2 }),577 validateProps({ val: PropTypes.integerRange.greaterThan(0) }, { val: 0 }),578 validateProps({ val: PropTypes.integerRange.greaterThanOrEqual(0) }, { val: -5 }),579 validateProps({ val: PropTypes.integerRange.lessThan(0) }, { val: 4 }),580 validateProps({ val: PropTypes.integerRange.lessThan(0) }, { val: 0 }),581 validateProps({ val: PropTypes.integerRange.lessThanOrEqual(0) }, { val: 2 })582 ]583 for (const validItem of valid) {584 expect(validItem).toMatchObject(validTypeCheck())585 }586 for (const invalidItem of [...invalid, ...validRangeButNonIntegers]) {587 expect(invalidItem).toMatchObject(invalidTypeCheck())588 }589 expect(() => validateProps({ val: PropTypes.integerRange(0) }, { val: 3 })).toThrow(PropTypesValidatorErrorBase)590 expect(() => validateProps({ val: PropTypes.integerRange.inclusive(0) }, { val: 3 })).toThrow(PropTypesValidatorErrorBase)591 expect(() => validateProps({ val: PropTypes.integerRange.exclusive(0) }, { val: 3 })).toThrow(PropTypesValidatorErrorBase)592 expect(() => validateProps({ val: PropTypes.integerRange.greaterThan(0, 1) }, { val: 3 })).toThrow(PropTypesValidatorErrorBase)593 expect(() => validateProps({ val: PropTypes.integerRange.greaterThanOrEqual(0, 1) }, { val: 3 })).toThrow(PropTypesValidatorErrorBase)594 expect(() => validateProps({ val: PropTypes.integerRange.lessThan(0, 1) }, { val: 3 })).toThrow(PropTypesValidatorErrorBase)595 expect(() => validateProps({ val: PropTypes.integerRange.lessThanOrEqual(0, 1) }, { val: 3 })).toThrow(PropTypesValidatorErrorBase)596 })597 it(`${prefix}.stringMatching`, () => {598 const valid = [599 validateProps({ val: PropTypes.stringMatching(/a|b/) }, { val: 'a' }),600 validateProps({ val: PropTypes.stringMatching(/a|b/) }, { val: 'b' }),601 validateProps({ val: PropTypes.stringMatching(/a|b/g) }, { val: 'b' }),602 validateProps({ val: PropTypes.stringMatching(/a|b/) }, { val: 'abc' }),603 validateProps({ val: PropTypes.stringMatching(/a|b/) }, { val: 'cbbc' }),604 validateProps({ val: PropTypes.stringMatching(/a|b/g) }, { val: 'cbbc' }),605 validateProps({ val: PropTypes.stringMatching(/^a$/) }, { val: 'a' }),606 validateProps({ val: PropTypes.stringMatching(/^a$/g) }, { val: 'a' })607 ]608 const invalid = [609 validateProps({ val: PropTypes.stringMatching(/a|b/) }, { val: 'x' }),610 validateProps({ val: PropTypes.stringMatching(/a|b/g) }, { val: 'x' }),611 validateProps({ val: PropTypes.stringMatching(/^a$/) }, { val: ' a ' }),612 validateProps({ val: PropTypes.stringMatching(/^a$/g) }, { val: ' a ' }),613 validateProps({ val: PropTypes.stringMatching(/^a$/g) }, { val: 2 }),614 validateProps({ val: PropTypes.stringMatching(/^a$/g).isRequired }, { val: null })615 ]616 for (const validItem of valid) {617 expect(validItem).toMatchObject(validTypeCheck())618 }619 for (const invalidItem of invalid) {620 expect(invalidItem).toMatchObject(invalidTypeCheck())621 }622 expect(() => validateProps({ val: PropTypes.stringMatching(2) }, { val: 'a' })).toThrow(PropTypesValidatorErrorBase)623 })624 it(`${prefix}.oneOf`, () => {625 const valid = [626 validateProps({ val: PropTypes.oneOf(['a', 'b']) }, { val: 'a' }),627 validateProps({ val: PropTypes.oneOf(['a', 'b']) }, { val: 'b' }),628 validateProps({ val: PropTypes.oneOf(['a', 'b']) }, { val: 'b' }),629 validateProps({ val: PropTypes.oneOf(['a', 4]) }, { val: 4 })630 ]631 const invalid = [632 validateProps({ val: PropTypes.oneOf(['a', 'b']) }, { val: 'c' }),633 validateProps({ val: PropTypes.oneOf(['a', 'b']) }, { val: [] }),634 validateProps({ val: PropTypes.oneOf([PropTypes.string, PropTypes.number]) }, { val: 5 })635 ]636 for (const validItem of valid) {637 expect(validItem).toMatchObject(validTypeCheck())638 }639 for (const invalidItem of invalid) {640 expect(invalidItem).toMatchObject(invalidTypeCheck())641 }642 expect(() => validateProps({ val: PropTypes.oneOf('a') }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)643 expect(() => validateProps({ val: PropTypes.oneOf(['a', 'b']) }, { val: 'b' })).not.toThrow(PropTypesValidatorErrorBase)644 })645 it(`${prefix}.oneOfType`, () => {646 const valid = [647 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }, { val: 'a' }),648 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }, { val: 5 }),649 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.array]) }, { val: [] }),650 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]) }, { val: ['a'] }),651 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string))]) }, { val: { a: ['a'] } })652 ]653 const invalid = [654 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }, { val: /a|b/ }),655 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) }, { val: [] }),656 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.array]) }, { val: {} }),657 validateProps({ val: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]) }, { val: [5] })658 ]659 for (const validItem of valid) {660 expect(validItem).toMatchObject(validTypeCheck())661 }662 for (const invalidItem of invalid) {663 expect(invalidItem).toMatchObject(invalidTypeCheck())664 }665 expect(() => validateProps({ val: PropTypes.oneOfType('a') }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)666 expect(() => validateProps({ val: PropTypes.oneOfType(['a', 'b']) }, { val: 'b' })).not.toThrow(PropTypesValidatorErrorBase)667 })668 it(`${prefix}.arrayOf`, () => {669 const valid = [670 validateProps({ val: PropTypes.arrayOf(PropTypes.string) }, { val: ['a', 'b'] }),671 validateProps({ val: PropTypes.arrayOf(PropTypes.number) }, { val: [5, 6] }),672 validateProps({ val: PropTypes.arrayOf(PropTypes.shape({ a: PropTypes.string, b: PropTypes.number })) }, { val: [{ a: 'a', b: 2 }, { a: 'aaa', b: 222 }] }),673 validateProps({ val: PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])) }, { val: ['a', 'a', 'a', 'b', 'b'] }),674 validateProps({ val: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.number)])) }, { val: ['a', 'b', [1, 2, 3], 'c', 'd'] })675 ]676 const invalid = [677 validateProps({ val: PropTypes.arrayOf(PropTypes.string) }, { val: [1] }),678 validateProps({ val: PropTypes.arrayOf(PropTypes.number) }, { val: ['5'] }),679 //validateProps({ val: PropTypes.arrayOf(PropTypes.shape({ a: PropTypes.string, b: PropTypes.number })) }, { val: [{ a: 4, b: 'a' }, { a: 3, b: 'a' }] }),680 validateProps({ val: PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])) }, { val: ['a', 'a', 'a', 'b', 'c'] }),681 validateProps({ val: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.number)])) }, { val: [5, 'b', ['a', 2, 3], 'c', 'd'] })682 ]683 for (const validItem of valid) {684 expect(validItem).toMatchObject(validTypeCheck())685 }686 for (const invalidItem of invalid) {687 expect(invalidItem).toMatchObject(invalidTypeCheck())688 }689 expect(() => validateProps({ val: PropTypes.arrayOf() }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)690 })691 it(`${prefix}.objectOf`, () => {692 const valid = [693 validateProps({ val: PropTypes.objectOf(PropTypes.string) }, { val: { x: 'a', y: 'b' } }),694 validateProps({ val: PropTypes.objectOf(PropTypes.number) }, { val: { a: 1, b: 2 } }),695 validateProps({ val: PropTypes.objectOf(PropTypes.shape({ a: PropTypes.string, b: PropTypes.number })) }, { val: { a: { a: 'a', b: 5 } } }),696 validateProps({ val: PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])) }, { val: { a: 'a', b: 'b', c: 'b', d: 'b', e: 'a', f: 'a' } }),697 validateProps({ val: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.number)])) }, { val: { a: 'a', b: 'b', c: 'c', d: [1, 2, 3], e: 'a' } })698 ]699 const invalid = [700 validateProps({ val: PropTypes.objectOf(PropTypes.string) }, { val: { a: 4 } }),701 validateProps({ val: PropTypes.objectOf(PropTypes.number) }, { val: { a: 'a' } }),702 //validateProps({ val: PropTypes.objectOf(PropTypes.shape({ a: PropTypes.string, b: PropTypes.number })) }, { val: { a: { a: 'a', b: 'b' } } }),703 validateProps({ val: PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])) }, { val: { a: 'a', b: 'b', c: 'c' } }),704 validateProps({ val: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.number)])) }, { val: { a: 'a', b: [3, 4, 'a'], c: 3 } })705 ]706 for (const validItem of valid) {707 expect(validItem).toMatchObject(validTypeCheck())708 }709 for (const invalidItem of invalid) {710 expect(invalidItem).toMatchObject(invalidTypeCheck())711 }712 expect(() => validateProps({ val: PropTypes.arrayOf() }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)713 })714 it(`${prefix}.instanceOf`, () => {715 const valid = [716 validateProps({ val: PropTypes.instanceOf(TestClassA) }, { val: new TestClassA() }),717 validateProps({ val: PropTypes.instanceOf(TestClassBase) }, { val: new TestClassBase() }),718 validateProps({ val: PropTypes.instanceOf(TestClassBase) }, { val: new TestClassA() })719 ]720 const invalid = [721 validateProps({ val: PropTypes.instanceOf(TestClassA) }, { val: 'a' }),722 validateProps({ val: PropTypes.instanceOf(TestClassBase) }, { val: 'b' }),723 validateProps({ val: PropTypes.instanceOf(TestClassBase) }, { val: 'c' })724 ]725 for (const validItem of valid) {726 expect(validItem).toMatchObject(validTypeCheck())727 }728 for (const invalidItem of invalid) {729 expect(invalidItem).toMatchObject(invalidTypeCheck())730 }731 function testFunction() {732 return true733 }734 expect(() => validateProps({ val: PropTypes.instanceOf('a') }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)735 expect(() => validateProps({ val: PropTypes.instanceOf(() => {}) }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)736 expect(() => validateProps({ val: PropTypes.instanceOf(new testFunction()) }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)737 })738 it(`${prefix}.shape`, () => {739 const valid = [740 validateProps({ val: PropTypes.shape({ a: PropTypes.string }) }, { val: { a: 'a' } }),741 validateProps({ val: PropTypes.shape({ a: PropTypes.string }) }, { val: { a: 'a', b: [] } }),742 validateProps({ val: PropTypes.shape({ a: PropTypes.string, b: PropTypes.string }) }, { val: { a: 'a', b: null } }),743 validateProps({ val: PropTypes.shape({ a: PropTypes.string, b: PropTypes.number }) }, { val: { a: 'a', b: 3 } }),744 validateProps({ val: PropTypes.shape({ a: PropTypes.string, b: PropTypes.shape({ a: PropTypes.array }) }) }, { val: { a: 'a', b: { a: [] } } }),745 validateProps({ val: PropTypes.shape({ a: PropTypes.string, b: PropTypes.shape({ a: PropTypes.instanceOf(TestClassBase)}) }) }, { val: { a: 'a', b: { a: new TestClassBase() } } })746 ]747 const invalid = [748 validateProps({ val: PropTypes.shape({ a: PropTypes.string }) }, { val: { a: 4 } }),749 validateProps({ val: PropTypes.shape({ a: PropTypes.number }) }, { val: { a: 'a' } }),750 validateProps({ val: PropTypes.shape({ a: PropTypes.number.isRequired }) }, { val: { a: null } })751 ]752 for (const validItem of valid) {753 expect(validItem).toMatchObject(validTypeCheck())754 }755 for (const invalidItem of invalid) {756 expect(invalidItem).toMatchObject(invalidTypeCheck())757 }758 expect(() => validateProps({ val: PropTypes.shape(PropTypes.number) }, { val: 45 })).toThrow(PropTypesValidatorErrorBase)759 expect(() => validateProps({ val: PropTypes.shape(PropTypes.string) }, { val: 'b' })).toThrow(PropTypesValidatorErrorBase)760 expect(() => validateProps({ val: PropTypes.shape([PropTypes.string]) }, { val: ['a'] })).toThrow(PropTypesValidatorErrorBase)761 })762 it(`${prefix}.customProp`, () => {763 const valid = [764 validateProps({ val: PropTypes.customProp(() => true, 'anything') }, { val: 'anything' }),765 validateProps({ val: PropTypes.customProp(value => value === 'anything' || value > 5, 'anything') }, { val: 8 }),766 validateProps({ val: PropTypes.customProp(value => value === 'anything' || value > 5, 'anything') }, { val: 'anything' }),767 validateProps({ val: PropTypes.customProp((value, key) => key === 'val' && true, 'anything') }, { val: 'anything' })768 ]769 const invalid = [770 validateProps({ val: PropTypes.customProp(() => false, 'nothing') }, { val: 'anything' }),771 validateProps({ val: PropTypes.customProp(value => value > 5, 'something') }, { val: 4 })772 ]773 for (const validItem of valid) {774 expect(validItem).toMatchObject(validTypeCheck())775 }776 for (const invalidItem of invalid) {777 expect(invalidItem).toMatchObject(invalidTypeCheck())778 }779 expect(() => validateProps({ val: PropTypes.customProp(5) }, { val: 45 })).toThrow(PropTypesValidatorErrorBase)780 expect(() => validateProps({ val: PropTypes.customProp(() => true, 5) }, { val: 45 })).toThrow(PropTypesValidatorErrorBase)781 expect(() => validateProps({ val: PropTypes.customProp(() => true, '') }, { val: 45 })).toThrow(PropTypesValidatorErrorBase)782 })783 })...

Full Screen

Full Screen

webhooks.spec.js

Source:webhooks.spec.js Github

copy

Full Screen

...24 httpMock.restore();25 });26 describe('#validateProps', () => {27 it('should throw an error if props are not provided', () => {28 expect(() => api.validateProps()).to.throw(Error, noPropsMessage);29 });30 it('should throw an error if props are empty', () => {31 expect(() => api.validateProps({})).to.throw(Error, noPropsMessage);32 });33 it('should throw an error if target is not provided and required', () => {34 expect(() => api.validateProps({35 event: 'message'36 }, true)).to.throw(Error, noTargetMessage);37 });38 it('should not throw an error if target is provided and required', () => {39 expect(() => api.validateProps({40 target: webhookUrl,41 event: 'message'42 }, true)).to.not.throw;43 });44 it('should throw an error if props url target is malformed', () => {45 expect(() => api.validateProps({46 target: malformedWebhookUrl,47 event: 'message'48 })).to.throw(Error, malformedTargetUrl);49 });50 it('should not throw an error if props are provided and target is not required', () => {51 expect(() => api.validateProps({52 event: 'message'53 })).to.not.throw;54 });55 });56 describe('#list', () => {57 it('should call http', () => {58 return api.list().then(() => {59 const fullUrl = `${serviceUrl}/webhooks`;60 httpSpy.should.have.been.calledWith('GET', fullUrl, undefined, httpHeaders);61 });62 });63 it('should return an error if app token in auth', (done) => {64 const badApi = new WebhooksApi(serviceUrl, getAuthenticationHeaders({65 appToken: 'some-token'...

Full Screen

Full Screen

existsSchemaUpdate.js

Source:existsSchemaUpdate.js Github

copy

Full Screen

1/* global MESSAGE,_ */2const {3 SERVER_ERROR, MODELS_UPDATED,4} = require('../../constants/message').message;5const { validateProperties } = require('./util');6const { existingSchemaUpdateValidation } = require('../util/validation/schema');7const {8 VALIDATION_MESSAGES, DEFAULT_FIELDS, DEFAULT_TABLE_NAME, DATA_TYPES,9} = require('../../constants/schema');10const {11 getDefaultFieldsForMongoDB, reOrderSchemaJson,12} = require('./util/staticData');13const { PROPS } = require('../../constants/dataTypes/props');14/**15 *16 * Function used for validate request.17 * @description :: Find Documentation @ http://validatejs.org/18 * @return mixed :: If error occurred then return array of errors else return undefined | null19 */20/*21 * async function validateData(data) {22 * const constraints = {23 */24/*25 * applicationId: {26 * presence: true,27 * type: 'string',28 * },29 * models: {30 * presence: true,31 * type: 'array',32 * },33 * };34 */35// const errors = validate(data, constraints);36/*37 * if (errors) {38 * return errors;39 * }40 */41/*42 * return null;43 * }44 */45const existsSchemaUpdate = (schemaRepo) => async (params) => {46 try {47 const {48 value, error,49 } = existingSchemaUpdateValidation(params);50 if (error) {51 return {52 data: null,53 code: MESSAGE.BAD_REQUEST.code,54 message: error,55 };56 }57 params = value;58 let modelErrors = [];59 const success = [];60 await Promise.all(params.models.map(async (model) => {61 if (model.isUploadedFile === true) {62 const schemaFilter = {63 find: {64 applicationId: params.applicationId,65 _id: model.schemaId,66 },67 };68 const schema = await schemaRepo.get(schemaFilter);69 if (!schema) {70 modelErrors.push({71 modelName: model.modelName,72 error: VALIDATION_MESSAGES.MODEL_NOT_FOUND,73 });74 } else {75 const validateProps = await validateProperties([76 {77 modelName: model.modelName,78 schemaJson: model.schemaJson,79 },80 ]);81 if (validateProps && (validateProps.errors && _.size(validateProps.errors) > 0)) {82 modelErrors.push(validateProps.errors);83 }84 if (validateProps?.originJson && _.size(validateProps.originJson) > 0) {85 model.schemaJson = _.cloneDeep(validateProps.originJson[0].schemaJson);86 }87 Object.keys(model.schemaJson).forEach((key) => {88 if (model.schemaJson[key].type && model.schemaJson[key].description && model.schemaJson[key].type.toUpperCase() === 'JSON') {89 model.schemaJson[key] = _.cloneDeep(model.schemaJson[key].description);90 } else if (model.schemaJson[key].type && model.schemaJson[key].description && _.isArray(model.schemaJson[key].description) && model.schemaJson[key].type.toUpperCase() === 'ARRAY') {91 model.schemaJson[key] = [_.cloneDeep(model.schemaJson[key].description[0])];92 }93 });94 const lowerSchemaJsonKeys = Object.keys(model.schemaJson).map((key) => key.toLowerCase());95 const defaultFields = await getDefaultFieldsForMongoDB();96 Object.keys(defaultFields).forEach((field) => {97 if (!_.includes(lowerSchemaJsonKeys, field.toLowerCase())) {98 model.schemaJson[field] = defaultFields[field];99 }100 });101 _.map(Object.keys(model.schemaJson), (key) => {102 if ((key.toLowerCase() === DEFAULT_FIELDS.ADDED_BY || key.toLowerCase() === DEFAULT_FIELDS.UPDATED_BY)) {103 if (typeof model.schemaJson[key] === 'string' && model.schemaJson[key].toLowerCase() === DATA_TYPES.OBJECTID.value.toLowerCase()) {104 model.schemaJson[key] = { type: model.schemaJson[key] };105 model.schemaJson[key][PROPS.REF] = DEFAULT_TABLE_NAME;106 } else if (model?.schemaJson[key]?.type && model?.schemaJson[key]?.type.toLowerCase() === DATA_TYPES.OBJECTID.value.toLowerCase()) {107 if (!model.schemaJson[key][PROPS.REF]) {108 model.schemaJson[key][PROPS.REF] = DEFAULT_TABLE_NAME;109 }110 }111 }112 });113 const updateModelInput = { schemaJson: model.schemaJson };114 if (updateModelInput?.schemaJson && !_.isEmpty(updateModelInput.schemaJson)) {115 updateModelInput.schemaJson = await reOrderSchemaJson(_.cloneDeep(updateModelInput.schemaJson));116 }117 const schemaUpdate = await schemaRepo.update(model.schemaId, updateModelInput);118 if (schemaUpdate) {119 success.push(schemaUpdate.toObject());120 } else {121 modelErrors.push({122 modelName: model.modelName,123 error: VALIDATION_MESSAGES.UPDATE_MODEL_ERROR,124 });125 }126 }127 }128 }));129 modelErrors = _.cloneDeep(_.flattenDeep(_.uniq(modelErrors)));130 return {131 ...MODELS_UPDATED,132 data: {133 error: modelErrors,134 success,135 },136 };137 } catch (err) {138 // eslint-disable-next-line no-console139 // console.log('error', err);140 return { ...SERVER_ERROR };141 // return { ...SERVER_ERROR, data: err.toString() };142 }143};...

Full Screen

Full Screen

props.test.js

Source:props.test.js Github

copy

Full Screen

...82});83describe('validateProps', () => {84 it('recognizes an unknown prop', () => {85 const prop = '__x';86 validateProps({[prop]: true});87 expect(console.warn).toHaveBeenCalledWith(88 ...getFormattedMessage(89 [90 `\`${prop}\``,91 "is not a valid prop. You may have spelled it incorrectly, or if it's",92 'a plugin, forgot to pass it in an array as props.plugins.',93 '\n\n',94 'All props: https://atomiks.github.io/tippyjs/v6/all-props/\n',95 'Plugins: https://atomiks.github.io/tippyjs/v6/plugins/',96 ].join(' ')97 )98 );99 });100 it('handles included plugin props', () => {101 const prop = 'followCursor';102 const plugins = [{name: prop, fn: () => ({})}];103 validateProps({[prop]: true});104 expect(console.warn).toHaveBeenCalledWith(105 ...getFormattedMessage(106 [107 `\`${prop}\``,108 "is not a valid prop. You may have spelled it incorrectly, or if it's",109 'a plugin, forgot to pass it in an array as props.plugins.',110 '\n\n',111 'All props: https://atomiks.github.io/tippyjs/v6/all-props/\n',112 'Plugins: https://atomiks.github.io/tippyjs/v6/plugins/',113 ].join(' ')114 )115 );116 console.warn.mockClear();117 validateProps({[prop]: true}, plugins);118 expect(console.warn).not.toHaveBeenCalled();119 });120 it('handles custom plugin props', () => {121 const prop = '__custom';122 const plugins = [{name: prop, fn: () => ({})}];123 validateProps({[prop]: true});124 expect(console.warn).toHaveBeenCalledWith(125 ...getFormattedMessage(126 [127 `\`${prop}\``,128 "is not a valid prop. You may have spelled it incorrectly, or if it's",129 'a plugin, forgot to pass it in an array as props.plugins.',130 '\n\n',131 'All props: https://atomiks.github.io/tippyjs/v6/all-props/\n',132 'Plugins: https://atomiks.github.io/tippyjs/v6/plugins/',133 ].join(' ')134 )135 );136 console.warn.mockClear();137 validateProps({[prop]: true}, plugins);138 expect(console.warn).not.toHaveBeenCalled();139 });...

Full Screen

Full Screen

validate.js

Source:validate.js Github

copy

Full Screen

1/** @jsx dom */2import assert from 'assert'3import {dom,deku} from '../../'4import {mount} from '../helpers'5function div() {6 return <div></div>;7}8describe('validation', function () {9 it('should validate missing props when first rendered', function(done){10 var Component = {11 render: div,12 propTypes: {13 'text': { type: 'string' }14 }15 }16 var app = deku()17 app.option('validateProps', true)18 app.mount(<Component />);19 mount(app, null, function(e){20 assert.equal(e.message, 'Missing property: text');21 done();22 })23 })24 it('should validate props types when first rendered', function(done){25 var Component = {26 render: div,27 propTypes: {28 'text': { type: 'string' }29 }30 }31 var app = deku()32 app.option('validateProps', true)33 app.mount(<Component text={true} />);34 mount(app, null, function(e){35 assert.equal(e.message, 'Invalid property type: text');36 done();37 })38 })39 it('should validate unexpected prop values when first rendered', function (done) {40 var Component = {41 render: div,42 propTypes: {43 'text': { type: 'string', expects: ['foo', 'bar', 'baz'] }44 }45 }46 var app = deku()47 app.option('validateProps', true)48 app.mount(<Component text="raz" />);49 mount(app, null, function(e){50 assert.equal(e.message, 'Invalid property value: text');51 done();52 })53 });54 it('should validate expected prop values when first rendered', function () {55 var Component = {56 render: div,57 propTypes: {58 'text': { type: 'string', expects: ['foo', 'bar', 'baz'] }59 }60 }61 var app = deku()62 app.option('validateProps', true)63 app.mount(<Component text="foo" />);64 mount(app)65 });66 it('should skip optional props when first rendered', function(){67 var Component = {68 render: div,69 propTypes: {70 'text': { type: 'string', optional: true }71 }72 }73 var app = deku()74 app.option('validateProps', true)75 app.mount(<Component />);76 mount(app)77 })78 it('should validate unknown properties', function(done){79 var Component = {80 render: div81 }82 var app = deku()83 .option('validateProps', true)84 .mount(<Component text="foo" />);85 mount(app, null, function(e){86 assert.equal(e.message, 'Unexpected property: text');87 done();88 })89 })90 it('should not validate if the option is not set', function () {91 var Component = {92 render: div93 }94 var app = deku()95 .option('validateProps', false)96 .mount(<Component text="foo" />);97 mount(app)98 });99 it('should validate nested types', function (done) {100 var Component = {101 render: div,102 propTypes: {103 'data': {104 type: {105 'text': { type: 'string' }106 }107 }108 }109 }110 var app = deku()111 app.option('validateProps', true)112 app.mount(<Component data={{ text: true }} />);113 mount(app, null, function(e){114 assert.equal(e.message, 'Invalid property type: data.text');115 done();116 })117 });118 it('should validate missing nested types', function (done) {119 var Component = {120 render: div,121 propTypes: {122 'data': {123 type: {124 'text': { type: 'string' }125 }126 }127 }128 }129 var app = deku()130 app.option('validateProps', true)131 app.mount(<Component />);132 mount(app, null, function(e){133 assert.equal(e.message, 'Missing property: data');134 done();135 })136 });137 it('should allow optional nested types', function () {138 var Component = {139 render: div,140 propTypes: {141 'data': {142 type: {143 'text': { type: 'string', optional: true }144 }145 }146 }147 }148 var app = deku()149 app.option('validateProps', true)150 app.mount(<Component data={{}} />);151 mount(app)152 });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...6 samplefac: 10,7 netsize: 256,8 format: 'rgb'9 }10 expect(validateProps(props)).toBe(true)11 })12 it('returns `false` if the sampling factor is missing', function () {13 expect(validateProps({samplefac: NaN, netsize: 16, format: 'hex'})).toBe(false)14 })15 it('returns `false` if the sampling factor is below the minimum', function () {16 expect(validateProps({samplefac: 0, netsize: 16, format: 'hex'})).toBe(false)17 })18 it('returns `false` if the sampling factor is above the maximum', function () {19 expect(validateProps({samplefac: 31, netsize: 16, format: 'hex'})).toBe(false)20 })21 it('returns `false` if the network size is missing', function () {22 expect(validateProps({samplefac: 10, netsize: NaN, format: 'hex'})).toBe(false)23 })24 it('returns `false` if the network size is below the minimum', function () {25 expect(validateProps({samplefac: 10, netsize: 3, format: 'hex'})).toBe(false)26 })27 it('returns `false` if the network size is above the maximum', function () {28 expect(validateProps({samplefac: 10, netsize: 257, format: 'hex'})).toBe(false)29 })30 it('returns `false` if the format is not supported', function () {31 expect(validateProps({samplefac: 10, netsize: 16, format: 'rgba'})).toBe(false)32 })33 it('returns `false` if the `custom` flag is present', function () {34 expect(validateProps({samplefac: 10, netsize: 16, format: 'rgb', custom: true})).toBe(false)35 })36 })...

Full Screen

Full Screen

seed.js

Source:seed.js Github

copy

Full Screen

1import { ValidateProps } from '@/api-lib/constants';2import {3 findUserByEmail,4 findUserByUsername,5 insertRole,6 insertUser,7 findRoleByRoleName,8} from '@/api-lib/db';9import { database, validateBody } from '@/api-lib/middlewares';10import { ncOpts } from '@/api-lib/nc';11import { slugUsername } from '@/lib/user';12import nc from 'next-connect';13import isEmail from 'validator/lib/isEmail';14import normalizeEmail from 'validator/lib/normalizeEmail';15const handler = nc(ncOpts);16handler.use(database);17handler.get(18 // validateBody({19 // type: 'object',20 // properties: {21 // roleName: ValidateProps.role.roleName,22 // C: ValidateProps.role.C,23 // R: ValidateProps.role.R,24 // U: ValidateProps.role.U,25 // D: ValidateProps.role.D,26 // },27 // required: ['roleName', 'C', 'R', 'U', 'D'],28 // additionalProperties: false,29 // }),30 async (req, res) => {31 const { roleName, C, R, U, D } = {32 roleName: 'Customer',33 C: '1',34 R: '1',35 U: '1',36 D: '1',37 };38 if (await findRoleByRoleName(req.db, roleName)) {39 res40 .status(403)41 .json({ error: { message: 'The roleName has already been taken.' } });42 return;43 }44 const role = await insertRole(req.db, { roleName, C, R, U, D });45 const role2 = await insertRole(req.db, {46 roleName: 'Customer2',47 C: '1',48 R: '1',49 U: '1',50 D: '1',51 });52 const role3 = await insertRole(req.db, {53 roleName: 'Customer3',54 C: '1',55 R: '1',56 U: '1',57 D: '1',58 });59 res.json({ role });60 }61);...

Full Screen

Full Screen

validate.test.js

Source:validate.test.js Github

copy

Full Screen

...6 container = document.querySelectorAll('.container');7});8describe('validate props', () => {9 it('return true without options', () => {10 expect(validateProps()).toBe(false);11 });12 it('target must be object type', () => {13 expect(validateProps({ target: '.something' })).toBe(false);14 });15 it('data must be required and array of object type.', () => {16 expect(validateProps({ target: container })).toBe(false);17 expect(validateProps({ target: container, data: {} })).toBe(false);18 expect(validateProps({ target: container, data: [{}] })).toBe(false);19 expect(validateProps({ target: container, ...sampleProps })).toBe(true);20 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { validateProps } = require('playwright/lib/server/supplements/utils/validation');2const { validateProps } = require('playwright/lib/server/supplements/utils/validation');3const { validateProps } = require('playwright/lib/server/supplements/utils/validation');4const { validateProps } = require('playwright/lib/server/supplements/utils/validation');5const { validateProps } = require('playwright/lib/server/supplements/utils/validation');6const { validateProps } = require('playwright/lib/server/supplements/utils/validation');7const { validateProps } = require('playwright/lib/server/supplements/utils/validation');8const { validateProps } = require('playwright/lib/server/supplements/utils/validation');9const { validateProps } = require('playwright/lib/server/supplements/utils/validation');10const { validateProps } = require('playwright/lib/server/supplements/utils/validation');11const { validateProps } = require('playwright/lib/server/supplements/utils/validation');12const { validateProps } = require('playwright/lib/server/s

Full Screen

Using AI Code Generation

copy

Full Screen

1const { validateProps } = require('playwright/lib/utils/validator');2const { Page } = require('playwright');3const { assert } = require('chai');4describe('Playwright Internal API', () => {5 it('validateProps', () => {6 const page = new Page();7 validateProps(page, 'Page', { foo: 'string' });8 validateProps(page, 'Page', { foo: 'string', bar: 'number' });9 validateProps(page, 'Page', { foo: 'string', bar: 'number', baz: 'boolean' });10 validateProps(page, 'Page', { foo: 'string', bar: 'number', baz: 'boolean', qux: 'object' });11 validateProps(page, 'Page', { foo: 'string', bar: 'number', baz: 'boolean', qux: 'object', quux: 'function' });12 validateProps(page, 'Page', { foo: 'string', bar: 'number', baz: 'boolean', qux: 'object', quux: 'function', corge: 'symbol' });13 validateProps(page, 'Page', { foo: 'string', bar: 'number', baz: 'boolean', qux: 'object', quux: 'function', corge: 'symbol', grault: 'undefined' });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { validateProps } = require('@playwright/test/lib/server/frames');2const page = await context.newPage();3const frame = page.mainFrame();4console.log(frame.url());5const { validateProps } = require('@playwright/test/lib/server/frames');6const page = await context.newPage();7const frame = page.mainFrame();8console.log(frame.url());9const { validateProps } = require('@playwright/test/lib/server/frames');10const page = await context.newPage();11const frame = page.mainFrame();12console.log(frame.url());13const page = await context.newPage();14const page = await context.newPage();15const page = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { validateProps } = require('playwright-core/lib/server/supplements/utils/validate');2const { assert } = require('chai');3const options = {4 waldo: Symbol('waldo'),5 fred: () => {},6 plugh: {},7};8const result = validateProps(options, {9 foo: { type: 'string' },10 baz: { type: 'number' },11 qux: { type: 'string', nullable: true },12 quuz: { type: 'boolean' },13 corge: { type: 'boolean' },14 grault: { type: 'null' },15 garply: { nullable: true },16 waldo: { type: 'symbol' },17 fred: { type: 'function' },18 plugh: { type: 'object' },19 xyzzy: { type: 'array' },20});21assert.deepEqual(result, {22 waldo: Symbol('waldo'),23 fred: () => {},24 plugh: {},25});26const { validateProps } = require('playwright-core/lib/server/supplements/utils/validate');27const { assert } = require('chai');28const options = {29 waldo: Symbol('waldo'),30 fred: () => {},31 plugh: {},32};33const result = validateProps(options, {34 foo: { type: 'string' },35 baz: { type: 'number' },36 qux: { type: 'string', nullable: true },37 quuz: { type: 'boolean' },38 corge: { type: 'boolean' },39 grault: { type: 'null' },

Full Screen

Using AI Code Generation

copy

Full Screen

1const { validateProps } = require('@playwright/test').internal;2const { MyComponent } = require('./component');3const props = {4 onClick: () => console.log('clicked!'),5};6validateProps(MyComponent, props);7const { Component } = require('react');8class MyComponent extends Component {9 render() {10 return <div id={this.props.id} onClick={this.props.onClick} />;11 }12}13module.exports = { MyComponent };14const { validateProps } = require('@playwright/test').internal;15const { MyComponent } = require('./component');16const props = {17 onClick: () => console.log('clicked!'),18};19validateProps(MyComponent, props);20const { Component } = require('react');21class MyComponent extends Component {22 render() {23 return <div id={this.props.id} onClick={this.props.onClick} />;24 }25}26module.exports = { MyComponent };

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful