|
| 1 | +import fc, { Arbitrary } from 'fast-check'; |
| 2 | +import { replace } from '../src'; |
| 3 | + |
| 4 | +const EachSimpleType = [ |
| 5 | + ['string', fc.string()], |
| 6 | + ['integers', fc.integer()], |
| 7 | +] as const; |
| 8 | + |
| 9 | +describe.each(EachSimpleType)('Simple replacements works for %p', (_, arb: Arbitrary<any>) => { |
| 10 | + test('Should replace simple types', () => { |
| 11 | + fc.assert( |
| 12 | + fc.property(arb, fc.func(arb), (s, f) => { |
| 13 | + return replace(f, (t: string): t is any => true)(s) === f(s); |
| 14 | + }), |
| 15 | + ); |
| 16 | + }); |
| 17 | +}); |
| 18 | + |
| 19 | +describe.each(EachSimpleType)('Simple replacements works for arrays of %p', (_, arb: Arbitrary<any>) => { |
| 20 | + test('Should replace only elements', () => { |
| 21 | + fc.assert( |
| 22 | + fc.property(fc.array(arb), fc.func(arb), (arr, f) => { |
| 23 | + const obtainedResult = replace(f, (t): t is any => !Array.isArray(t))(arr); |
| 24 | + const realResult = arr.map((v) => f(v)); |
| 25 | + expect(obtainedResult).toStrictEqual(realResult); |
| 26 | + }), |
| 27 | + ); |
| 28 | + }); |
| 29 | +}); |
| 30 | + |
| 31 | +describe.each(EachSimpleType)('Simple replacements works for objects of %p', (_, arb: Arbitrary<any>) => { |
| 32 | + test('Should replace only properties', () => { |
| 33 | + fc.assert( |
| 34 | + fc.property(fc.dictionary(fc.string(), arb), fc.func(arb), (obj, f) => { |
| 35 | + const realResult = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, f(v)])); |
| 36 | + const obtainedResult = replace(f, (t): t is any => !Array.isArray(t) && typeof t !== 'object')(obj); |
| 37 | + |
| 38 | + expect(obtainedResult).toStrictEqual(realResult); |
| 39 | + }), |
| 40 | + ); |
| 41 | + }); |
| 42 | +}); |
| 43 | + |
| 44 | +describe('Ignoring values', () => { |
| 45 | + const f = (v: any) => { |
| 46 | + throw new Error(); |
| 47 | + }; |
| 48 | + test('should leave json objects alone', () => { |
| 49 | + const throwOnReplace = replace(f, (t): t is any => false); |
| 50 | + fc.assert( |
| 51 | + fc.property(fc.jsonObject(), (json) => { |
| 52 | + expect(() => expect(throwOnReplace(json)).toStrictEqual(json)).not.toThrow(); |
| 53 | + }), |
| 54 | + ); |
| 55 | + }); |
| 56 | + |
| 57 | + test('Should leave numbers unchanged when searching for strings', () => { |
| 58 | + const throwOnReplace = replace(f, (t): t is string => typeof t === 'string'); |
| 59 | + const objectArbitrary = fc.object({ maxDepth: 4, withTypedArray: true, values: [fc.integer()] }); |
| 60 | + fc.assert( |
| 61 | + fc.property(objectArbitrary, (obj) => { |
| 62 | + expect(() => throwOnReplace(obj)).not.toThrow(); |
| 63 | + }), |
| 64 | + ); |
| 65 | + }); |
| 66 | +}); |
0 commit comments