Socialify

Folder ..

Viewing address.spec.ts
658 lines (537 loc) • 20.9 KB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
import { afterEach, describe, expect, it } from 'vitest';
import { faker } from '../dist/cjs';

const seededRuns = [
  {
    seed: 42,
    expectations: {
      city: 'Lake Valentine',
      cityPrefix: 'West',
      citySuffix: 'bury',
      cityName: 'Gulfport',
      streetName: 'Valentine Isle',
      streetPrefix: 'b',
      streetSuffix: 'Isle',
      streetAddressDigits: 4,
      fullStreetAddress: '7917 Lauryn Spur Apt. 410',
      secondaryAddress: 'Apt. 791',
      county: 'Berkshire',
      country: 'Haiti',
      countryCode: 'GY',
      state: 'Maine',
      stateAbbr: 'ME',
      zipCode: '79177',
      direction: 'South',
      directionNonAbbr: 'South',
      directionAbbr: 'S',
      ordinalDirection: 'Northwest',
      ordinalDirectionAbbr: 'NW',
      cardinalDirection: 'East',
      cardinalDirectionAbbr: 'E',
      timeZone: 'Europe/Amsterdam',
    },
  },
  {
    seed: 1337,
    expectations: {
      city: 'South Carmelo',
      cityPrefix: 'East',
      citySuffix: 'berg',
      cityName: 'Dubuque',
      streetName: 'Carmelo Forks',
      streetPrefix: 'a',
      streetSuffix: 'Forks',
      streetAddressDigits: 5,
      fullStreetAddress: '51225 Hammes Lodge Apt. 552',
      secondaryAddress: 'Apt. 512',
      county: 'Bedfordshire',
      country: 'Equatorial Guinea',
      countryCode: 'EH',
      state: 'Indiana',
      stateAbbr: 'IN',
      zipCode: '51225',
      direction: 'South',
      directionNonAbbr: 'South',
      directionAbbr: 'S',
      ordinalDirection: 'Northwest',
      ordinalDirectionAbbr: 'NW',
      cardinalDirection: 'East',
      cardinalDirectionAbbr: 'E',
      timeZone: 'Africa/Casablanca',
    },
  },
  {
    seed: 1211,
    expectations: {
      city: 'La Crosse',
      cityPrefix: 'Port',
      citySuffix: 'side',
      cityName: 'Urbana',
      streetName: 'Trantow Via',
      streetPrefix: 'c',
      streetSuffix: 'Via',
      streetAddressDigits: 3,
      fullStreetAddress: '487 Zieme Flat Apt. 616',
      secondaryAddress: 'Suite 487',
      county: 'Cambridgeshire',
      country: 'Uganda',
      countryCode: 'UM',
      state: 'Washington',
      stateAbbr: 'WA',
      zipCode: '48721-9061',
      direction: 'Southwest',
      directionNonAbbr: 'Southwest',
      directionAbbr: 'SW',
      ordinalDirection: 'Southwest',
      ordinalDirectionAbbr: 'SW',
      cardinalDirection: 'West',
      cardinalDirectionAbbr: 'W',
      timeZone: 'Asia/Magadan',
    },
  },
];

const NON_SEEDED_BASED_RUN = 5;

describe('address', () => {
  afterEach(() => {
    faker.locale = 'en';
  });

  for (const { seed, expectations } of seededRuns) {
    describe(`seed: ${seed}`, () => {
      it('city()', () => {
        faker.seed(seed);

        const city = faker.address.city();
        expect(city).toEqual(expectations.city);
      });

      it('cityPrefix()', () => {
        faker.seed(seed);

        const cityPrefix = faker.address.cityPrefix();
        expect(cityPrefix).toEqual(expectations.cityPrefix);
      });

      it('citySuffix()', () => {
        faker.seed(seed);

        const citySuffix = faker.address.citySuffix();
        expect(citySuffix).toEqual(expectations.citySuffix);
      });

      it('cityName()', () => {
        faker.seed(seed);

        const cityName = faker.address.cityName();
        expect(cityName).toEqual(expectations.cityName);
      });

      it('streetName()', () => {
        faker.seed(seed);

        const street_name = faker.address.streetName();
        expect(street_name).toEqual(expectations.streetName);
      });

      describe('streetAddress()', () => {
        it('should return a digit street number', () => {
          faker.seed(seed);

          const address = faker.address.streetAddress();
          const parts = address.split(' ');

          expect(
            parts[0].length,
            `The street number should have ${expectations.streetAddressDigits} digits`
          ).toStrictEqual(expectations.streetAddressDigits);
        });

        describe('when useFulladdress is true', () => {
          it('adds a secondary address to the result', () => {
            faker.seed(seed);

            const address = faker.address.streetAddress(true);
            expect(address).toEqual(expectations.fullStreetAddress);
          });
        });
      });

      it('streetPrefix()', () => {
        faker.seed(seed);

        const streetPrefix = faker.address.streetPrefix();
        expect(streetPrefix).toEqual(expectations.streetPrefix);
      });

      it('streetSuffix()', () => {
        faker.seed(seed);

        const streetSuffix = faker.address.streetSuffix();
        expect(streetSuffix).toEqual(expectations.streetSuffix);
      });

      describe('secondaryAddress()', () => {
        it('randomly chooses an Apt or Suite number', () => {
          faker.seed(seed);

          const address = faker.address.secondaryAddress();
          expect(address).toEqual(expectations.secondaryAddress);
        });
      });

      describe('county()', () => {
        it('returns random county', () => {
          faker.seed(seed);

          const county = faker.address.county();
          expect(county).toEqual(expectations.county);
        });
      });

      describe('country()', () => {
        it('returns random country', () => {
          faker.seed(seed);

          const country = faker.address.country();
          expect(country).toEqual(expectations.country);
        });
      });

      describe('countryCode()', () => {
        it('returns random countryCode', () => {
          faker.seed(seed);

          const countryCode = faker.address.countryCode();
          expect(countryCode).toEqual(expectations.countryCode);
        });
      });

      describe('state()', () => {
        it('returns random state', () => {
          faker.seed(seed);

          const state = faker.address.state();
          expect(state).toEqual(expectations.state);
        });
      });

      describe('stateAbbr()', () => {
        it('returns random stateAbbr', () => {
          faker.seed(seed);

          const stateAbbr = faker.address.stateAbbr();
          expect(stateAbbr).toEqual(expectations.stateAbbr);
        });
      });

      describe('zipCode()', () => {
        it('returns random zipCode', () => {
          faker.seed(seed);

          const zipCode = faker.address.zipCode();
          expect(zipCode).toEqual(expectations.zipCode);
        });
      });

      describe('direction()', () => {
        it('returns random direction', () => {
          faker.seed(seed);

          const direction = faker.address.direction();
          const expected = expectations.direction;

          expect(
            direction,
            `The random direction should be equal to ${expected}`
          ).toBe(expected);
        });

        it('should not return abbreviation when useAbbr is false', () => {
          faker.seed(seed);

          const direction = faker.address.direction(false);
          const expected = expectations.directionNonAbbr;

          expect(
            direction,
            `The abbreviation of direction when useAbbr is false should be equal ${expected}. Current is ${direction}`
          ).toBe(expected);
        });

        it('returns abbreviation when useAbbr is true', () => {
          faker.seed(seed);

          const direction = faker.address.direction(true);
          const expected = expectations.directionAbbr;

          expect(
            direction,
            `The abbreviation of direction when useAbbr is true should be equal ${expected}. Current is ${direction}`
          ).toBe(expected);
        });
      });

      describe('ordinalDirection()', () => {
        it('returns random ordinal direction', () => {
          faker.seed(seed);

          const ordinalDirection = faker.address.ordinalDirection();
          const expected = expectations.ordinalDirection;

          expect(
            ordinalDirection,
            `The ransom ordinal direction should be equal ${expected}. Current is ${ordinalDirection}`
          ).toBe(expected);
        });

        it('returns abbreviation when useAbbr is true', () => {
          faker.seed(seed);

          const ordinalDirection = faker.address.ordinalDirection(true);
          const expected = expectations.ordinalDirectionAbbr;

          expect(
            ordinalDirection,
            `The ordinal direction when useAbbr is true should be equal ${expected}. Current is ${ordinalDirection}`
          ).toBe(expected);
        });
      });

      describe('cardinalDirection()', () => {
        it('returns random cardinal direction', () => {
          faker.seed(seed);

          const cardinalDirection = faker.address.cardinalDirection();
          const expected = expectations.cardinalDirection;

          expect(
            cardinalDirection,
            `The random cardinal direction should be equal ${expected}. Current is ${cardinalDirection}`
          ).toBe(expected);
        });

        it('returns abbreviation when useAbbr is true', () => {
          faker.seed(seed);

          const cardinalDirection = faker.address.cardinalDirection(true);
          const expected = expectations.cardinalDirectionAbbr;

          expect(
            cardinalDirection,
            `The cardinal direction when useAbbr is true should be equal ${expected}. Current is ${cardinalDirection}`
          ).toBe(expected);
        });
      });

      describe('timeZone()', () => {
        it('returns random timeZone', () => {
          faker.seed(seed);

          const timeZone = faker.address.timeZone();
          expect(timeZone).toEqual(expectations.timeZone);
        });
      });
    });
  }

  // Create and log-back the seed for debug purposes
  faker.seed(Math.ceil(Math.random() * 1_000_000_000));

  describe(`random seeded tests for seed ${faker.seedValue}`, () => {
    for (let i = 1; i <= NON_SEEDED_BASED_RUN; i++) {
      describe('countryCode()', () => {
        it('returns random alpha-3 countryCode', () => {
          const countryCode = faker.address.countryCode('alpha-3');

          expect(countryCode).toBeTruthy();
          expect(
            countryCode.length,
            'The countryCode should be 3 characters long'
          ).toBe(3);
        });
      });

      describe('zipCode()', () => {
        it('returns random zipCode - user specified format', () => {
          let zipCode = faker.address.zipCode('?#? #?#');

          expect(zipCode).match(/^[A-Za-z]\d[A-Za-z]\s\d[A-Za-z]\d$/);

          // try another format
          zipCode = faker.address.zipCode('###-###');

          expect(zipCode).match(/^\d{3}-\d{3}$/);
        });

        it('returns zipCode with proper locale format', () => {
          // we'll use the en_CA locale..
          faker.locale = 'en_CA';
          const zipCode = faker.address.zipCode();

          expect(zipCode).match(/^[A-Za-z]\d[A-Za-z]\s?\d[A-Za-z]\d$/);
        });
      });

      describe('zipCodeByState()', () => {
        it('returns zipCode valid for specified State', () => {
          faker.locale = 'en_US';
          const states = ['IL', 'GA', 'WA'];

          const zipCode1 = faker.address.zipCodeByState(states[0]);
          expect(zipCode1).greaterThanOrEqual(60001);
          expect(zipCode1).lessThanOrEqual(62999);

          const zipCode2 = faker.address.zipCodeByState(states[1]);
          expect(zipCode2).greaterThanOrEqual(30001);
          expect(zipCode2).lessThanOrEqual(31999);

          const zipCode3 = faker.address.zipCodeByState(states[2]);
          expect(zipCode3).greaterThanOrEqual(98001);
          expect(zipCode3).lessThanOrEqual(99403);
        });
      });

      describe('latitude()', () => {
        it('returns random latitude', () => {
          for (let i = 0; i < 100; i++) {
            const latitude = faker.address.latitude();

            expect(typeof latitude).toBe('string');

            const latitude_float = parseFloat(latitude);

            expect(latitude_float).greaterThanOrEqual(-90.0);
            expect(latitude_float).lessThanOrEqual(90.0);
          }
        });

        it('returns latitude with min and max and default precision', () => {
          for (let i = 0; i < 100; i++) {
            const latitude = faker.address.latitude(-5, 5);

            expect(typeof latitude).toBe('string');
            expect(
              latitude.split('.')[1].length,
              'The precision of latitude should be 4 digits'
            ).toBe(4);

            const latitude_float = parseFloat(latitude);

            expect(latitude_float).greaterThanOrEqual(-5);
            expect(latitude_float).lessThanOrEqual(5);
          }
        });

        it('returns random latitude with custom precision', () => {
          for (let i = 0; i < 100; i++) {
            const latitude = faker.address.latitude(undefined, undefined, 7);

            expect(typeof latitude).toBe('string');
            expect(
              latitude.split('.')[1].length,
              'The precision of latitude should be 7 digits'
            ).toBe(7);

            const latitude_float = parseFloat(latitude);

            expect(latitude_float).greaterThanOrEqual(-180);
            expect(latitude_float).lessThanOrEqual(180);
          }
        });
      });

      describe('longitude()', () => {
        it('returns random longitude', () => {
          for (let i = 0; i < 100; i++) {
            const longitude = faker.address.longitude();

            expect(typeof longitude).toBe('string');

            const longitude_float = parseFloat(longitude);

            expect(longitude_float).greaterThanOrEqual(-180);
            expect(longitude_float).lessThanOrEqual(180);
          }
        });

        it('returns random longitude with min and max and default precision', () => {
          for (let i = 0; i < 100; i++) {
            const longitude = faker.address.longitude(100, -30);

            expect(typeof longitude).toBe('string');
            expect(
              longitude.split('.')[1].length,
              'The precision of longitude should be 4 digits'
            ).toBe(4);

            const longitude_float = parseFloat(longitude);

            expect(longitude_float).greaterThanOrEqual(-30);
            expect(longitude_float).lessThanOrEqual(100);
          }
        });

        it('returns random longitude with custom precision', () => {
          for (let i = 0; i < 100; i++) {
            const longitude = faker.address.longitude(undefined, undefined, 7);

            expect(typeof longitude).toBe('string');
            expect(
              longitude.split('.')[1].length,
              'The precision of longitude should be 7 digits'
            ).toBe(7);

            const longitude_float = parseFloat(longitude);

            expect(longitude_float).greaterThanOrEqual(-180);
            expect(longitude_float).lessThanOrEqual(180);
          }
        });
      });

      describe('direction()', () => {
        it('returns abbreviation when useAbbr is true', () => {
          const direction = faker.address.direction(true);
          const lengthDirection = direction.length;
          const prefixErrorMessage =
            'The abbreviation of direction when useAbbr is true should';

          expect(
            typeof direction,
            `${prefixErrorMessage} be of type string. Current is ${typeof direction}`
          ).toBe('string');
          expect(lengthDirection).lessThanOrEqual(2);
        });
      });

      describe('ordinalDirection()', () => {
        it('returns abbreviation when useAbbr is true', () => {
          const ordinalDirection = faker.address.ordinalDirection(true);
          const expectedType = 'string';
          const ordinalDirectionLength = ordinalDirection.length;
          const prefixErrorMessage =
            'The ordinal direction when useAbbr is true should';

          expect(
            typeof ordinalDirection,
            `${prefixErrorMessage} be equal ${expectedType}. Current is ${typeof ordinalDirection}`
          ).toBe(expectedType);
          expect(ordinalDirectionLength).lessThanOrEqual(2);
        });
      });

      describe('cardinalDirection()', () => {
        it('returns abbreviation when useAbbr is true', () => {
          const cardinalDirection = faker.address.cardinalDirection(true);
          const expectedType = 'string';
          const cardinalDirectionLength = cardinalDirection.length;
          const prefixErrorMessage =
            'The cardinal direction when useAbbr is true should';

          expect(
            typeof cardinalDirection,
            `${prefixErrorMessage} be of type ${expectedType}. Current is ${typeof cardinalDirection}`
          ).toBe(expectedType);
          expect(cardinalDirectionLength).lessThanOrEqual(2);
        });
      });

      describe('nearbyGPSCoordinate()', () => {
        it('should return random gps coordinate within a distance of another one', () => {
          function haversine(lat1, lon1, lat2, lon2, isMetric) {
            function degreesToRadians(degrees) {
              return degrees * (Math.PI / 180.0);
            }
            function kilometersToMiles(miles) {
              return miles * 0.621371;
            }
            const R = 6378.137;
            const dLat = degreesToRadians(lat2 - lat1);
            const dLon = degreesToRadians(lon2 - lon1);
            const a =
              Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(degreesToRadians(lat1)) *
                Math.cos(degreesToRadians(lat2)) *
                Math.sin(dLon / 2) *
                Math.sin(dLon / 2);
            const distance = R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

            return isMetric ? distance : kilometersToMiles(distance);
          }

          let latFloat1: number;
          let lonFloat1: number;
          let isMetric: boolean;

          for (let i = 0; i < 10000; i++) {
            latFloat1 = parseFloat(faker.address.latitude());
            lonFloat1 = parseFloat(faker.address.longitude());
            const radius = Math.random() * 99 + 1; // range of [1, 100)
            isMetric = Math.round(Math.random()) == 1;

            const coordinate = faker.address.nearbyGPSCoordinate(
              [latFloat1, lonFloat1],
              radius,
              isMetric
            );

            expect(coordinate.length).toBe(2);
            expect(typeof coordinate[0]).toBe('string');
            expect(typeof coordinate[1]).toBe('string');

            const latFloat2 = parseFloat(coordinate[0]);
            expect(latFloat2).greaterThanOrEqual(-90.0);
            expect(latFloat2).lessThanOrEqual(90.0);

            const lonFloat2 = parseFloat(coordinate[1]);
            expect(lonFloat2).greaterThanOrEqual(-180.0);
            expect(lonFloat2).lessThanOrEqual(180.0);

            // Due to floating point math, and constants that are not extremely precise,
            // returned points will not be strictly within the given radius of the input
            // coordinate. Using a error of 1.0 to compensate.
            const error = 1.0;
            const actualDistance = haversine(
              latFloat1,
              lonFloat1,
              latFloat2,
              lonFloat2,
              isMetric
            );
            expect(actualDistance).lessThanOrEqual(radius + error);
          }
        });

        it('should return near metric coordinates when radius is undefined', () => {
          const latitude = parseFloat(faker.address.latitude());
          const longitude = parseFloat(faker.address.longitude());
          const isMetric = true;

          const coordinate = faker.address.nearbyGPSCoordinate(
            [latitude, longitude],
            undefined,
            isMetric
          );

          expect(coordinate.length).toBe(2);
          expect(typeof coordinate[0]).toBe('string');
          expect(typeof coordinate[1]).toBe('string');

          const distanceToTarget =
            Math.pow(coordinate[0] - latitude, 2) +
            Math.pow(coordinate[1] - longitude, 2);

          expect(distanceToTarget).lessThanOrEqual(
            100 * 0.002 // 100 km ~= 0.9 degrees, we take 2 degrees
          );
        });

        it('should return near non metric coordinates when radius is undefined', () => {
          const latitude = parseFloat(faker.address.latitude());
          const longitude = parseFloat(faker.address.longitude());
          const isMetric = false;

          const coordinate = faker.address.nearbyGPSCoordinate(
            [latitude, longitude],
            undefined,
            isMetric
          );

          expect(coordinate.length).toBe(2);
          expect(typeof coordinate[0]).toBe('string');
          expect(typeof coordinate[1]).toBe('string');

          // const distanceToTarget =
          //   Math.pow(coordinate[0] - latitude, 2) +
          //   Math.pow(coordinate[1] - longitude, 2);

          // TODO @Shinigami92 2022-01-27: Investigate why this test sometimes fails
          // expect(distanceToTarget).lessThanOrEqual(
          //   100 * 0.002 * 1.6093444978925633 // 100 miles to km ~= 0.9 degrees, we take 2 degrees
          // );
        });
      });
    }
  });
});