moment#valueOf TypeScript Examples

The following examples show how to use moment#valueOf. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocationHistoryService.test.ts    From hamagen-react-native with MIT License 4 votes vote down vote up
// const {subtract, date, month, year} = momentSubFn

describe('LocationHistoryService', () => {
  describe('getLoadingHTML', () => {
    test('Is valid HTML', () => {
      const { DOMParser } = jest.requireActual('xmldom');
      const loadedHTML = getLoadingHTML();
      // check if parsing the dom works
      expect(new DOMParser().parseFromString(loadedHTML)).toBeDefined();
    });
  });

  describe('getLastNrDaysKmlUrls', () => {
    test('make an array for 2 weeks', () => {
      subtract.mockImplementation(() => ({
        date,
        month,
        year,
      }));
      expect(getLastNrDaysKmlUrls()).toHaveLength(14);
      // length of 2 weeks
      expect(subtract).toBeCalledTimes(14);
    });
  });

  describe('kmlToGeoJson', () => {
    beforeEach(() => {
      kml.mockClear();
    });

    test('no text', () => {
      kml.mockReturnValue({ features: [] });
      expect(kmlToGeoJson()).toHaveLength(0);
      expect(kmlToGeoJson('')).toHaveLength(0);
    });

    test('filters results', () => {
      const features = [
        {
          geometry: {
            type: 'Point',

          },
          properties: {
            timespan: {
              begin: 1,
              end: 2
            },
            coordinates: [1, 1],
            Category: 'should ignore from test',

          }
        },
      ];
      kml.mockReturnValue({ features });
      expect(kmlToGeoJson('')).toHaveLength(0);
    });

    test('make proper sample obj', () => {
      const features = [
        {
          geometry: {
            type: 'Point',
            coordinates: [34.8077312410001, 32.1154996280001],
          },
          properties: {
            OBJECTID: 1720,
            Key_Field: 1720,
            Name: 'חולה 15',
            Place: 'קלאוזנר 14, רמת אביב (קלפי ייעודית למבודדי בית)',
            Comments:
                        'על מי ששעת הגעתו לקלפי זו היתה בין השעות 10:15-11:15 להאריך את הבידוד הביתי ל14 יום מיום הבחירות',
            POINT_X: 34.80773124,
            POINT_Y: 32.11549963,
            timespan: {
              begin: 1583144100000,
              end: 1583147700000
            },
            sourceOID: 1,
            stayTimes: '10:15-11:15',
          },
        }
      ];
      valueOf.mockReturnValueOnce(1).mockReturnValueOnce(2);
      kml.mockReturnValue({ features });
      encode.mockReturnValueOnce(1);

      expect(kmlToGeoJson('')).toEqual([{
        startTime: 1,
        endTime: 2,
        long: 34.8077312410001,
        lat: 32.1154996280001,
        geoHash: 1,
        accuracy: 0,
        wifiHash: ''
      }]);
    });
  });

  describe('insertToSampleDB', () => {
    beforeEach(() => {
      dispatch.mockClear();
      actionSpy.mockClear();
    });
    // we assume insertToSampleDB will be called with array > 0 so we will not check
    const sampleData = [
      {
        startTime: 1583346600000,
        endTime: 1583351500000,
        accuracy: 10,
        long: 35.535289000000034,
        lat: 32.78675100000004,
      },
      {
        startTime: 1584468100000,
        endTime: 1584568739000,
        accuracy: 5,
        long: 34.901541,
        lat: 32.132502,
      },

    ];

    test('two data point', async () => {
      expect(await insertToSampleDB(sampleData)).toBeUndefined();
      // sha was called with all the sample data
      expect(sha256).toHaveBeenCalledWith(JSON.stringify(sampleData[0]));
      expect(sha256).toHaveBeenCalledWith(JSON.stringify(sampleData[1]));

      expect(db.insertBulkSamples).toBeCalledTimes(1);
      expect(db.insertBulkSamples).toBeCalledWith(sampleData.reduce((curr, sample) => `${curr}(${sample.lat},${sample.long},${sample.accuracy},${sample.startTime},${sample.endTime},'${sample.geoHash}','','a'),`, '').slice(0, -1));

      expect(actionSpy).toBeCalledTimes(1);
    });

    test('with FIRST_POINT_TS', async () => {
      await AsyncStorage.setItem(FIRST_POINT_TS, (sampleData[0].startTime - 2000).toString());

      expect(await insertToSampleDB(sampleData)).toBeUndefined();

      expect(AsyncStorage.setItem).toBeCalledWith(SHOULD_HIDE_LOCATION_HISTORY, 'true');
      expect(actionSpy).toBeCalledTimes(1);
      expect(dispatch).toBeCalledTimes(1);
    });
  });
});
Example #2
Source File: Tracker.test.ts    From hamagen-react-native with MIT License 4 votes vote down vote up
describe('Tracker', () => {
  // ====================================
  //  Check all TimeOverlapping Scenario
  // ====================================

  test('isTimeOverlapping()', () => {
    // Check user time not intersects before sick time range
    expect(
      tracker.isTimeOverlapping(
        { startTime: oneHour, endTime: 2 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(false);

    // Check user no intersects same end time
    expect(
      tracker.isTimeOverlapping(
        { startTime: 8 * oneHour, endTime: 10 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(false);

    // Check user end time intersects sick range
    expect(
      tracker.isTimeOverlapping(
        { startTime: 8 * oneHour, endTime: 12 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(true);

    // Check sick user full time inside user time
    expect(
      tracker.isTimeOverlapping(
        { startTime: 9 * oneHour, endTime: 22 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(true);

    // Check user full time in sick range
    expect(
      tracker.isTimeOverlapping(
        { startTime: 11 * oneHour, endTime: 12 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(true);

    // Check user start time intersects with sick time
    expect(
      tracker.isTimeOverlapping(
        { startTime: 15 * oneHour, endTime: 22 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(true);

    // Check no intersects but same end time
    expect(
      tracker.isTimeOverlapping(
        { startTime: 20 * oneHour, endTime: 22 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(false);

    // Check user time not intersects after sick time
    expect(
      tracker.isTimeOverlapping(
        { startTime: 21 * oneHour, endTime: 26 * oneHour, ...userRecordExtras },
        sickRecord,
      ),
    ).toBe(false);

    // ================================================
    //  Check the milliseconds overlapping restriction
    // ================================================

    // Check smaller than intersect milliseconds
    expect(
      tracker.isTimeOverlapping(
        {
          startTime: 8 * oneHour,
          endTime: 10 * oneHour + smallerThanIntersectMilliseconds,
          ...userRecordExtras
        },
        sickRecord,
      ),
    ).toBe(false);

    // Check larger than intersect milliseconds
    expect(
      tracker.isTimeOverlapping(
        {
          startTime: 9 * oneHour,
          endTime: 10 * oneHour + largerThanIntersectMilliseconds,
          ...userRecordExtras
        },
        sickRecord,
      ),
    ).toBe(true);

    // Check larger than intersect milliseconds
    expect(
      tracker.isTimeOverlapping(
        {
          startTime: 18 * oneHour + smallerThanIntersectMilliseconds,
          endTime: 21 * oneHour,
          ...userRecordExtras
        },
        sickRecord,
      ),
    ).toBe(true);
  });

  test('unitTestGeography()', () => {
    // South
    expect(
      tracker.isSpaceOverlapping({ long: 34.612383, lat: 31.307915, ...userRecordExtras2 }, sickRecord),
    ).toBe(true);
    expect(
      tracker.isSpaceOverlapping({ long: 34.612645, lat: 31.305848, ...userRecordExtras2 }, sickRecord),
    ).toBe(false);
    // West
    expect(
      tracker.isSpaceOverlapping({ long: 34.609032, lat: 31.311498, ...userRecordExtras2 }, sickRecord),
    ).toBe(true);
    expect(
      tracker.isSpaceOverlapping({ long: 34.604462, lat: 31.311608, ...userRecordExtras2 }, sickRecord),
    ).toBe(false);
    // North-East
    expect(
      tracker.isSpaceOverlapping({ long: 34.615315, lat: 31.312473, ...userRecordExtras2 }, sickRecord),
    ).toBe(true);
    expect(
      tracker.isSpaceOverlapping({ long: 34.618952, lat: 31.314902, ...userRecordExtras2 }, sickRecord),
    ).toBe(false);
  });

  test('unitTestIntersectingRecords()', async () => {
    fetch(config().dataUrl_utc, {
      headers: { 'Content-Type': 'application/json;charset=utf-8' },
    })
      .then(response => response.json())
      .then(async (responseJson) => {
        const myData = [
          {
            startTime: 1583144150000,
            endTime: 1583147700000,
            accuracy: 5,
            long: 34.807731241000056,
            lat: 32.115499628000066,
            geoHash: '',
            hash: '',
            wifiHash: ''
          },
          {
            startTime: 1583346600000,
            endTime: 1583351500000,
            accuracy: 10,
            long: 35.535289000000034,
            lat: 32.78675100000004,
            geoHash: '',
            hash: '',
            wifiHash: ''
          },
          {
            startTime: 1583346600000,
            endTime: 1583351500000,
            accuracy: 10,
            long: 37.535289000000034,
            lat: 32.78675100000004,
            geoHash: '',
            hash: '',
            wifiHash: ''
          },
          {
            startTime: 1584391600000,
            endTime: 1584396500000,
            accuracy: 10,
            long: 35.535289000000034,
            lat: 32.78675100000004,
            geoHash: '',
            hash: '',
            wifiHash: ''
          },
        ];

        const intersectingRecords = tracker.getIntersectingSickRecords(
          myData,
          responseJson,
        );

        expect(intersectingRecords.length).toEqual(2);
      });
  });

  test('queryDB()', async () => {
    const rows = ['data1', 'data2', 'data3'];
    const userLocationDB = new db.UserLocationsDatabase();
    userLocationDB.listSamples.mockResolvedValueOnce(rows);
    expect(tracker.queryDB()).resolves.toEqual(rows);
  });

  test('onSickPeopleNotify()', async () => {
    const sickDB = new db.IntersectionSickDatabase();
    const rows: any = [];
    sickDB.addSickRecord.mockResolvedValueOnce(rows);
    sickDB.containsObjectID.mockResolvedValueOnce(rows);
    // check he
    expect(tracker.onSickPeopleNotify(sickPeopleArray)).resolves.toEqual(
      undefined,
    );
    // check unsupported language
    NativeModules.SettingsManager.settings.AppleLocale = 'gh';
    expect(tracker.onSickPeopleNotify(sickPeopleArray)).resolves.toEqual(
      undefined,
    );

    constants.IS_IOS = false;
    expect(tracker.onSickPeopleNotify(sickPeopleArray)).resolves.toEqual(
      undefined,
    );
  });

  test('checkSickPeople() - good', async () => {
    const userLocationDB = new db.UserLocationsDatabase();
    const sampleData = [
      {
        startTime: 1584468100000,
        endTime: 1584568739000,
        accuracy: 5,
        long: 34.901541,
        lat: 32.132502,
      },
      {
        startTime: 1583346600000,
        endTime: 1583351500000,
        accuracy: 10,
        long: 35.535289000000034,
        lat: 32.78675100000004,
      },
    ];

    const responseJSON = {
      type: 'FeatureCollection',
      features: [
        {
          type: 'Feature',
          id: 1,
          geometry: {
            type: 'Point',
            coordinates: [34.901541, 32.132502],
          },
          properties: {
            OBJECTID: 1,
            Name: 'חולה 16',
            Place: 'ניקודה בקניון',
            Comments: 'בדיקה',
            POINT_X: 34.901541,
            POINT_Y: 32.132502,
            fromTime: 1584468000000,
            toTime: 1584568740000,
            sourceOID: 1,
            stayTimes: '18:00 - 10:00',
          },
        },
      ],
    };
    downloadAndVerifySigning.mockResolvedValueOnce(responseJSON);

    userLocationDB.listSamples.mockReturnValueOnce(Promise.resolve(sampleData));
    valueOf.mockReturnValueOnce(new Date().getTime());
    await tracker.checkSickPeople();
  });

  test('checkSickPeople() - NoData', async () => {
    const responseJSON = {
      features: 'asd',
    };
    downloadAndVerifySigning.mockResolvedValueOnce(responseJSON);
    const userLocationDB = new db.UserLocationsDatabase();
    userLocationDB.listSamples.mockReturnValueOnce(Promise.resolve([]));
    const getIntersectingSickRecordsByGeoHashSpy = jest.spyOn(tracker, 'getIntersectingSickRecordsByGeoHash');
    getIntersectingSickRecordsByGeoHashSpy.mockReturnValueOnce([]);
    await tracker.checkSickPeople();
    getIntersectingSickRecordsByGeoHashSpy.mockReset();
  });

  test('checkSickPeople() - fetch error', async () => {
    downloadAndVerifySigning.mockRejectedValueOnce();
    new db.UserLocationsDatabase().listSamples.mockResolvedValueOnce([]);
    // userLocationDB.listSamples.mockResolvedValueOnce([])

    await tracker.checkSickPeople();

    expect(onError).toBeCalledTimes(1);
    // make sure after all wont fail
    onError.mockClear();
  });

  test('startForegroundTimer()', async () => {
    const responseJSON = {
      features: 'asd',
    };

    const userLocationDB = new db.UserLocationsDatabase();
    userLocationDB.listSamples.mockResolvedValueOnce([]);

    downloadAndVerifySigning.mockResolvedValueOnce(responseJSON);


    await tracker.startForegroundTimer();
  });
});