From 857f60a3574e30ad4617b50a6181d4066b78e1bd Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 14:56:04 -0700 Subject: [PATCH] chore(core): manual fix linter reported errors under __tests__ --- .eslintrc.js | 1 + .../BackgroundProcessManager.test.ts | 72 +++++---- .../core/__tests__/Cache/StorageCache.test.ts | 4 +- .../Cache/StorageCacheCommon.test.ts | 46 +++--- .../__tests__/Cache/utils/CacheList.test.ts | 4 +- packages/core/__tests__/ConsoleLogger.test.ts | 10 +- packages/core/__tests__/DateUtils.test.ts | 21 ++- packages/core/__tests__/Hub.test.ts | 16 +- .../core/__tests__/JS-browser-runtime.test.ts | 3 +- packages/core/__tests__/Mutex.test.ts | 36 +++-- .../Platform/customUserAgent.test.ts | 14 +- packages/core/__tests__/Retry.test.ts | 4 +- packages/core/__tests__/ServiceWorker.test.ts | 10 +- packages/core/__tests__/Signer.test.ts | 32 ++-- .../clients/composeApiHandler.test.ts | 22 ++- .../clients/composeTransferHandler.test.ts | 12 +- packages/core/__tests__/clients/fetch.test.ts | 6 +- .../middleware/retry/middleware.test.ts | 10 +- .../__tests__/singleton/Singleton.test.ts | 33 ++--- .../__tests__/storage/CookieStorage.test.ts | 13 +- .../__tests__/storage/DefaultStorage.test.ts | 1 + .../__tests__/storage/SessionStorage.test.ts | 1 + packages/core/__tests__/utils.test.ts | 4 +- .../globalHelpers.native.test.ts | 9 +- .../queuedStorage.native.test.ts | 41 ++++-- .../utils/queuedStorage/queuedStorage.test.ts | 139 ++++++++++++++++-- 26 files changed, 368 insertions(+), 196 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index ba5a240f65f..7b4bda2f1e8 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -82,6 +82,7 @@ module.exports = { allow: [ // exceptions for core package 'phone_number', + 'search_indices', // exceptions for api packages 'graphql_headers', // exceptions for the legacy config diff --git a/packages/core/__tests__/BackgroundProcessManager.test.ts b/packages/core/__tests__/BackgroundProcessManager.test.ts index 71f893d56f5..75fa2bbc1e0 100644 --- a/packages/core/__tests__/BackgroundProcessManager.test.ts +++ b/packages/core/__tests__/BackgroundProcessManager.test.ts @@ -96,9 +96,9 @@ describe('BackgroundProcessManager', () => { const manager = new BackgroundProcessManager(); const resultPromise = manager.add(async () => { - return new Promise((resolve, raise) => { + return new Promise((resolve, reject) => { setTimeout(() => { - raise(new Error('a fuss')); + reject(new Error('a fuss')); }, 50); }); }); @@ -146,7 +146,7 @@ describe('BackgroundProcessManager', () => { const manager = new BackgroundProcessManager(); // add a job that will not have completed by the time we open() again - manager.add(async () => new Promise(unsleep => setTimeout(unsleep, 10))); + manager.add(async () => new Promise(resolve => setTimeout(resolve, 10))); // close, but don't want, because we want to prove that open() will wait // internally for close to resolve before re-opening. @@ -176,8 +176,15 @@ describe('BackgroundProcessManager', () => { expect(manager.isClosing).toBe(false); expect(manager.isClosed).toBe(false); - let unblock; - manager.add(async () => new Promise(_unblock => (unblock = _unblock))); + let unblock: () => void = () => { + // no op + }; + manager.add( + async () => + new Promise(resolve => { + unblock = resolve; + }), + ); expect(manager.state).toEqual(BackgroundProcessManagerState.Open); expect(manager.isOpen).toBe(true); @@ -195,7 +202,7 @@ describe('BackgroundProcessManager', () => { // promise layers handling by awaiting another promise before the // manager can register completion. - unblock(); + unblock?.(); await new Promise(process.nextTick); expect(manager.state).toEqual(BackgroundProcessManagerState.Closed); @@ -252,8 +259,8 @@ describe('BackgroundProcessManager', () => { let completed = false; const manager = new BackgroundProcessManager(); - const resultPromise = manager.add(async onTerminate => { - return new Promise((resolve, reject) => { + const _ = manager.add(async (onTerminate: Promise) => { + return new Promise((resolve, _reject) => { const timer = setTimeout(() => { // this is the happy path that we plan not to reach in // this test. @@ -290,8 +297,9 @@ describe('BackgroundProcessManager', () => { let completed = false; let thrown; const manager = new BackgroundProcessManager(); + const expectedError = new Error('badness happened'); - const resultPromise = manager.add(async onTerminate => { + const resultPromise = manager.add(async (onTerminate: Promise) => { return new Promise((resolve, reject) => { const timer = setTimeout(() => { // this is the happy path that we plan not to reach in @@ -305,7 +313,7 @@ describe('BackgroundProcessManager', () => { // or reject. onTerminate.then(() => { clearTimeout(timer); - reject('badness happened'); + reject(expectedError); }); }); }); @@ -329,7 +337,7 @@ describe('BackgroundProcessManager', () => { // then making sure the job really really didn't fire. expect(completed).toBe(false); - expect(thrown).toEqual('badness happened'); + expect(thrown).toEqual(expectedError); }); test('attempts to terminate all, but patiently waits for persistent jobs', async () => { @@ -341,7 +349,7 @@ describe('BackgroundProcessManager', () => { for (let i = 0; i < 10; i++) { const _i = i; results.push(false); - manager.add(async onTerminate => { + manager.add(async (onTerminate: Promise) => { return new Promise((resolve, reject) => { const timer = setTimeout(() => { results[_i] = true; @@ -357,7 +365,7 @@ describe('BackgroundProcessManager', () => { // remember, if a job *does* terminate, it still // needs resolve/reject to unblock `close()`. - _i > 5 ? resolve() : reject(); + _i > 5 ? resolve() : reject(new Error()); } }); }); @@ -371,7 +379,9 @@ describe('BackgroundProcessManager', () => { expect(results.length).toEqual(10); // sanity check expect(results.filter(v => v === true).length).toBe(5); expect(terminationAttemptCount).toEqual(10); - expect(resolutions.filter(r => r.status === 'rejected').length).toEqual(3); + expect( + resolutions.filter((r: any) => r.status === 'rejected').length, + ).toEqual(3); }); test('can be used to terminate other types of bg jobs, like zen subscriptions', async () => { @@ -418,7 +428,7 @@ describe('BackgroundProcessManager', () => { const manager = new BackgroundProcessManager(); let count = 0; - const subscription = new Observable(observer => { + const _ = new Observable(observer => { const interval = setInterval(() => { observer.next({}); }, 10); @@ -502,7 +512,7 @@ describe('BackgroundProcessManager', () => { // accumulate a bunch of close promises, only the first of which should // send the close signal, but all of which should await resolution. - const closes = [0, 1, 2, 3, 4, 5].map(i => manager.close()); + const closes = [0, 1, 2, 3, 4, 5].map(_ => manager.close()); // ensure everything has settled const resolved = await Promise.allSettled(closes); @@ -564,7 +574,7 @@ describe('BackgroundProcessManager', () => { const manager = new BackgroundProcessManager(); manager.add( - async () => new Promise(unsleep => setTimeout(unsleep, 1)), + async () => new Promise(resolve => setTimeout(resolve, 1)), 'async function', ); @@ -579,9 +589,9 @@ describe('BackgroundProcessManager', () => { const manager = new BackgroundProcessManager(); manager.add( - async onTerminate => - new Promise(finishJob => { - onTerminate.then(finishJob); + async (onTerminate: Promise) => + new Promise(resolve => { + onTerminate.then(resolve); }), 'cancelable async function', ); @@ -635,27 +645,31 @@ describe('BackgroundProcessManager', () => { const manager = new BackgroundProcessManager(); await manager.close(); - await expect(manager.add(async () => {}, 'some job')).rejects.toThrow( - 'some job', - ); + await expect( + manager.add(async () => { + // no-op + }, 'some job'), + ).rejects.toThrow('some job'); }); test('manager closed error shows names of pending items in error', async () => { const manager = new BackgroundProcessManager(); - let unblock; + let unblock: any; manager.add( - () => new Promise(_unblock => (unblock = _unblock)), + () => new Promise(resolve => (unblock = resolve)), 'blocking job', ); const close = manager.close(); - await expect(manager.add(async () => {}, 'some job')).rejects.toThrow( - 'blocking job', - ); + await expect( + manager.add(async () => { + // no-op + }, 'some job'), + ).rejects.toThrow('blocking job'); - unblock(); + unblock?.(); await close; }); }); diff --git a/packages/core/__tests__/Cache/StorageCache.test.ts b/packages/core/__tests__/Cache/StorageCache.test.ts index c30474f5374..f6615f7a38b 100644 --- a/packages/core/__tests__/Cache/StorageCache.test.ts +++ b/packages/core/__tests__/Cache/StorageCache.test.ts @@ -46,8 +46,8 @@ describe('StorageCache', () => { } } // create test helpers - const getStorageCache = (config?: CacheConfig) => - new StorageCacheTest(config); + const getStorageCache = (storageCacheConfig?: CacheConfig) => + new StorageCacheTest(storageCacheConfig); beforeAll(() => { mockGetCurrentSizeKey.mockReturnValue(currentSizeKey); diff --git a/packages/core/__tests__/Cache/StorageCacheCommon.test.ts b/packages/core/__tests__/Cache/StorageCacheCommon.test.ts index ea997dac41b..a1488ef71e9 100644 --- a/packages/core/__tests__/Cache/StorageCacheCommon.test.ts +++ b/packages/core/__tests__/Cache/StorageCacheCommon.test.ts @@ -26,7 +26,7 @@ describe('StorageCacheCommon', () => { warningThreshold: 0.8, }; // create spies - const loggerSpy = { + const loggerSpy: Record = { debug: jest.spyOn(ConsoleLogger.prototype, 'debug'), error: jest.spyOn(ConsoleLogger.prototype, 'error'), warn: jest.spyOn(ConsoleLogger.prototype, 'warn'), @@ -57,9 +57,9 @@ describe('StorageCacheCommon', () => { } } // create test helpers - const getStorageCache = (config?: CacheConfig) => + const getStorageCache = (storageCacheConfig?: CacheConfig) => new StorageCacheCommonTest({ - config, + config: storageCacheConfig, keyValueStorage: mockKeyValueStorage, }); @@ -464,8 +464,8 @@ describe('StorageCacheCommon', () => { describe('getItem()', () => { const value = 'value'; const cache = getStorageCache(config); - const key = 'key'; - const prefixedKey = `${keyPrefix}${key}`; + const testKey = 'key'; + const testPrefixedKey = `${keyPrefix}${testKey}`; beforeEach(() => { mockKeyValueStorageGetItem.mockReturnValue(null); @@ -476,11 +476,11 @@ describe('StorageCacheCommon', () => { JSON.stringify({ data: value }), ); - expect(await cache.getItem(key)).toBe(value); + expect(await cache.getItem(testKey)).toBe(value); expect(loggerSpy.debug).toHaveBeenCalledWith( - expect.stringContaining(`Get item: key is ${key}`), + expect.stringContaining(`Get item: key is ${testKey}`), ); - expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(prefixedKey); + expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(testPrefixedKey); }); it('aborts on empty key', async () => { @@ -508,22 +508,24 @@ describe('StorageCacheCommon', () => { }), ); - expect(await cache.getItem(key)).toBeNull(); - expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith(prefixedKey); + expect(await cache.getItem(testKey)).toBeNull(); + expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith( + testPrefixedKey, + ); }); it('returns null if not in cache', async () => { - expect(await cache.getItem(key)).toBeNull(); + expect(await cache.getItem(testKey)).toBeNull(); }); it('updates item visitedTime when fetched from cache', async () => { const item = { data: value }; mockKeyValueStorageGetItem.mockReturnValue(JSON.stringify(item)); - expect(await cache.getItem(key)).toBe(value); - expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(prefixedKey); + expect(await cache.getItem(testKey)).toBe(value); + expect(mockKeyValueStorageGetItem).toHaveBeenCalledWith(testPrefixedKey); expect(mockKeyValueStorageSetItem).toHaveBeenCalledWith( - prefixedKey, + testPrefixedKey, JSON.stringify({ ...item, visitedTime: currentTime }), ); }); @@ -531,7 +533,7 @@ describe('StorageCacheCommon', () => { it('execute a callback if specified when key not found in cache', async () => { mockGetByteLength.mockReturnValue(20); const callback = jest.fn(() => value); - expect(await cache.getItem(key, { callback })).toBe(value); + expect(await cache.getItem(testKey, { callback })).toBe(value); expect(callback).toHaveBeenCalled(); expect(mockKeyValueStorageSetItem).toHaveBeenCalled(); }); @@ -539,8 +541,8 @@ describe('StorageCacheCommon', () => { describe('removeItem()', () => { const cache = getStorageCache(config); - const key = 'key'; - const prefixedKey = `${keyPrefix}${key}`; + const testKey = 'key'; + const testPrefixedKey = `${keyPrefix}${testKey}`; beforeEach(() => { mockKeyValueStorageGetItem.mockReturnValue( @@ -549,11 +551,13 @@ describe('StorageCacheCommon', () => { }); it('removes an item', async () => { - await cache.removeItem(key); + await cache.removeItem(testKey); expect(loggerSpy.debug).toHaveBeenCalledWith( - expect.stringContaining(`Remove item: key is ${key}`), + expect.stringContaining(`Remove item: key is ${testKey}`), + ); + expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith( + testPrefixedKey, ); - expect(mockKeyValueStorageRemoveItem).toHaveBeenCalledWith(prefixedKey); }); it('aborts on empty key', async () => { @@ -574,7 +578,7 @@ describe('StorageCacheCommon', () => { it('does nothing if item not found', async () => { mockKeyValueStorageGetItem.mockReturnValue(null); - await cache.removeItem(key); + await cache.removeItem(testKey); expect(mockKeyValueStorageRemoveItem).not.toHaveBeenCalled(); }); }); diff --git a/packages/core/__tests__/Cache/utils/CacheList.test.ts b/packages/core/__tests__/Cache/utils/CacheList.test.ts index a8016a56c09..4bbede75fab 100644 --- a/packages/core/__tests__/Cache/utils/CacheList.test.ts +++ b/packages/core/__tests__/Cache/utils/CacheList.test.ts @@ -125,8 +125,8 @@ describe('CacheList', () => { test('get all keys in the list', () => { const list: CacheList = new CacheList(); const keys: string[] = ['0', '1', '2']; - for (let i = 0; i < keys.length; i++) { - list.insertItem(keys[i]); + for (const key of keys) { + list.insertItem(key); } const listKeys: string[] = list.getKeys(); diff --git a/packages/core/__tests__/ConsoleLogger.test.ts b/packages/core/__tests__/ConsoleLogger.test.ts index f0ed669a26e..80ccf7e82c9 100644 --- a/packages/core/__tests__/ConsoleLogger.test.ts +++ b/packages/core/__tests__/ConsoleLogger.test.ts @@ -25,16 +25,18 @@ describe('ConsoleLogger', () => { it('should do nothing when a non-logging category plugin is provided to addPluggable', () => { const provider = { - getCategoryName: function () { + getCategoryName: () => { return 'non-logging'; }, - getProviderName: function () { + getProviderName: () => { return 'lol'; }, - configure: function () { + configure: () => { return {}; }, - pushLogs: () => {}, + pushLogs: () => { + // no-op + }, } as LoggingProvider; const logger = new ConsoleLogger('name'); diff --git a/packages/core/__tests__/DateUtils.test.ts b/packages/core/__tests__/DateUtils.test.ts index d0ed93fd7fe..d42ee18f92a 100644 --- a/packages/core/__tests__/DateUtils.test.ts +++ b/packages/core/__tests__/DateUtils.test.ts @@ -1,16 +1,15 @@ import { DateUtils } from '../src/Signer/DateUtils'; -// Mock Date (https://github.com/facebook/jest/issues/2234#issuecomment-308121037) -const OriginalDate = Date; -// @ts-ignore Type 'typeof Date' is not assignable to type 'DateConstructor'. -Date = class extends Date { - // @ts-ignore Constructors for derived classes must contain a 'super' call.ts(2377) - constructor() { - return new OriginalDate('2020-01-01'); - } -}; - describe('DateUtils', () => { + beforeAll(() => { + jest.useFakeTimers(); + jest.setSystemTime(new Date('2020-01-01')); + }); + + afterAll(() => { + jest.useRealTimers(); + }); + describe('getDateWithClockOffset()', () => { it('should return a new Date()', () => { expect(DateUtils.getDateWithClockOffset()).toEqual(new Date()); @@ -63,7 +62,7 @@ describe('DateUtils', () => { it('should be true when over 5 minutes', () => { const serverDate = new Date(); - serverDate.setMinutes(5); + serverDate.setMinutes(5, 0, 1000); expect(DateUtils.isClockSkewed(serverDate)).toBe(true); }); diff --git a/packages/core/__tests__/Hub.test.ts b/packages/core/__tests__/Hub.test.ts index 216730b5254..b1250fe8c86 100644 --- a/packages/core/__tests__/Hub.test.ts +++ b/packages/core/__tests__/Hub.test.ts @@ -9,7 +9,9 @@ describe('Hub', () => { }); test('happy case', () => { - const listener = jest.fn(() => {}); + const listener = jest.fn(() => { + // no-op + }); Hub.listen('auth', listener); @@ -28,7 +30,9 @@ describe('Hub', () => { }); test('Protected channel', () => { - const listener = jest.fn(() => {}); + const listener = jest.fn(() => { + // no-op + }); Hub.listen('auth', listener); @@ -50,7 +54,9 @@ describe('Hub', () => { }); test('Protected channel - ui', () => { - const listener = jest.fn(() => {}); + const listener = jest.fn(() => { + // no-op + }); Hub.listen('ui', listener); @@ -67,7 +73,9 @@ describe('Hub', () => { ); }); test('Remove listener', () => { - const listener = jest.fn(() => {}); + const listener = jest.fn(() => { + // no-op + }); const unsubscribe = Hub.listen('auth', listener); diff --git a/packages/core/__tests__/JS-browser-runtime.test.ts b/packages/core/__tests__/JS-browser-runtime.test.ts index 372b902f10c..a82954d9733 100644 --- a/packages/core/__tests__/JS-browser-runtime.test.ts +++ b/packages/core/__tests__/JS-browser-runtime.test.ts @@ -9,12 +9,11 @@ describe('isBrowser build test', () => { // testing the Node.js process. const originalVersions = process.versions; beforeEach(() => { - // @ts-ignore + // @ts-expect-error test overrides delete global.process.versions; }); afterEach(() => { - // @ts-ignore global.process.versions = originalVersions; }); diff --git a/packages/core/__tests__/Mutex.test.ts b/packages/core/__tests__/Mutex.test.ts index 6a47360a6a8..b27615b4310 100644 --- a/packages/core/__tests__/Mutex.test.ts +++ b/packages/core/__tests__/Mutex.test.ts @@ -24,12 +24,12 @@ import { Mutex } from '../src/Mutex'; -describe('Mutex', function () { +describe('Mutex', () => { let mutex: Mutex; beforeEach(() => (mutex = new Mutex())); - test('ownership is exclusive', function () { + test('ownership is exclusive', () => { let flag = false; mutex.acquire().then(release => @@ -46,7 +46,7 @@ describe('Mutex', function () { }); }); - test('runExclusive passes result (immediate)', function () { + test('runExclusive passes result (immediate)', () => { return mutex .runExclusive(() => 10) .then(value => { @@ -54,7 +54,7 @@ describe('Mutex', function () { }); }); - test('runExclusive passes result (promise)', function () { + test('runExclusive passes result (promise)', () => { return mutex .runExclusive(() => Promise.resolve(10)) .then(value => { @@ -62,31 +62,35 @@ describe('Mutex', function () { }); }); - test('runExclusive passes rejection', function () { + test('runExclusive passes rejection', () => { + const expectedError = new Error('foo'); + return mutex - .runExclusive(() => Promise.reject('foo')) + .runExclusive(() => Promise.reject(expectedError)) .then( - () => Promise.reject('should have been rejected'), + () => Promise.reject(new Error('should have been rejected')), value => { - expect(value).toBe('foo'); + expect(value).toBe(expectedError); }, ); }); - test('runExclusive passes exception', function () { + test('runExclusive passes exception', () => { + const expectedError = new Error('foo'); + return mutex .runExclusive(() => { - throw 'foo'; + throw expectedError; }) .then( - () => Promise.reject('should have been rejected'), + () => Promise.reject(new Error('should have been rejected')), value => { - expect(value).toBe('foo'); + expect(value).toBe(expectedError); }, ); }); - test('runExclusive is exclusive', function () { + test('runExclusive is exclusive', () => { let flag = false; mutex.runExclusive( @@ -104,7 +108,7 @@ describe('Mutex', function () { }); }); - test('exceptions during runExclusive do not leave mutex locked', function () { + test('exceptions during runExclusive do not leave mutex locked', () => { let flag = false; mutex @@ -122,11 +126,11 @@ describe('Mutex', function () { }); }); - test('new mutex is unlocked', function () { + test('new mutex is unlocked', () => { expect(!mutex.isLocked()).toBe(true); }); - test('isLocked reflects the mutex state', async function () { + test('isLocked reflects the mutex state', async () => { const lock1 = mutex.acquire(); const lock2 = mutex.acquire(); diff --git a/packages/core/__tests__/Platform/customUserAgent.test.ts b/packages/core/__tests__/Platform/customUserAgent.test.ts index 707f1faf227..b891d2da041 100644 --- a/packages/core/__tests__/Platform/customUserAgent.test.ts +++ b/packages/core/__tests__/Platform/customUserAgent.test.ts @@ -1,4 +1,5 @@ import { + AdditionalDetails, AuthAction, Category, SetCustomUserAgentInput, @@ -18,15 +19,16 @@ const MOCK_STORAGE_UA_STATE: SetCustomUserAgentInput = { }; describe('Custom user agent utilities', () => { - let getCustomUserAgent; - let setCustomUserAgent; + let getCustomUserAgent: ( + category: string, + api: string, + ) => AdditionalDetails | undefined; + let setCustomUserAgent: (input: SetCustomUserAgentInput) => () => void; beforeEach(() => { jest.resetModules(); - getCustomUserAgent = - require('../../src/Platform/customUserAgent').getCustomUserAgent; - setCustomUserAgent = - require('../../src/Platform/customUserAgent').setCustomUserAgent; + ({ getCustomUserAgent } = require('../../src/Platform/customUserAgent')); + ({ setCustomUserAgent } = require('../../src/Platform/customUserAgent')); }); it('sets custom user agent state for multiple categories and APIs', () => { diff --git a/packages/core/__tests__/Retry.test.ts b/packages/core/__tests__/Retry.test.ts index 561865b7bc7..59a5ceca741 100644 --- a/packages/core/__tests__/Retry.test.ts +++ b/packages/core/__tests__/Retry.test.ts @@ -60,8 +60,8 @@ describe('retry', () => { } } - function delayFunction(attempt, args) { - receivedAttempt = attempt; + function delayFunction(attemptForDelayed: number, args: any[] | undefined) { + receivedAttempt = attemptForDelayed; receivedArgs = args; return 1; diff --git a/packages/core/__tests__/ServiceWorker.test.ts b/packages/core/__tests__/ServiceWorker.test.ts index 0e575ed5293..cdb04616d81 100644 --- a/packages/core/__tests__/ServiceWorker.test.ts +++ b/packages/core/__tests__/ServiceWorker.test.ts @@ -21,7 +21,7 @@ describe('ServiceWorker test', () => { }); test('fails when registering', async () => { (global as any).navigator.serviceWorker = { - register: () => Promise.reject('an error'), + register: () => Promise.reject(new Error('an error')), }; const serviceWorker = new ServiceWorker(); @@ -38,7 +38,13 @@ describe('ServiceWorker test', () => { const statuses = ['installing', 'waiting', 'active']; statuses.forEach(status => { test(`can register (${status})`, () => { - const bla = { [status]: { addEventListener: () => {} } }; + const bla = { + [status]: { + addEventListener: () => { + // no-op + }, + }, + }; (global as any).navigator.serviceWorker = { register: () => Promise.resolve(bla), }; diff --git a/packages/core/__tests__/Signer.test.ts b/packages/core/__tests__/Signer.test.ts index 9453703c2ca..9625b972783 100644 --- a/packages/core/__tests__/Signer.test.ts +++ b/packages/core/__tests__/Signer.test.ts @@ -48,22 +48,26 @@ describe('Signer.sign', () => { 'signs request with %s', ( _, - { url, ...request }, - { credentials, signingRegion, signingService }, + { url: testUrl, ...request }, + { + credentials: testCredentials, + signingRegion: testSigningRegion, + signingService: testSigningService, + }, expected, ) => { - const { accessKeyId, secretAccessKey, sessionToken } = credentials; + const { accessKeyId, secretAccessKey, sessionToken } = testCredentials; const accessInfo = { access_key: accessKeyId, secret_key: secretAccessKey, session_token: sessionToken, }; const serviceInfo = { - region: signingRegion, - service: signingService, + region: testSigningRegion, + service: testSigningService, }; const signedRequest = Signer.sign( - { ...request, url: url.toString() }, + { ...request, url: testUrl.toString() }, accessInfo as any, serviceInfo as any, ); @@ -156,22 +160,26 @@ describe('Signer.signUrl', () => { 'signs url with %s', ( _, - { url, ...request }, - { credentials, signingRegion, signingService }, + { url: testUrl, ...request }, + { + credentials: testCredentials, + signingRegion: testSigningRegion, + signingService: testSigningService, + }, expected, ) => { - const { accessKeyId, secretAccessKey, sessionToken } = credentials; + const { accessKeyId, secretAccessKey, sessionToken } = testCredentials; const accessInfo = { access_key: accessKeyId, secret_key: secretAccessKey, session_token: sessionToken, }; const serviceInfo = { - region: signingRegion, - service: signingService, + region: testSigningRegion, + service: testSigningService, }; const signedUrl = Signer.signUrl( - { ...request, url: url.toString() }, + { ...request, url: testUrl.toString() }, accessInfo, serviceInfo as any, ); diff --git a/packages/core/__tests__/clients/composeApiHandler.test.ts b/packages/core/__tests__/clients/composeApiHandler.test.ts index f9580604432..eeaec7ec17b 100644 --- a/packages/core/__tests__/clients/composeApiHandler.test.ts +++ b/packages/core/__tests__/clients/composeApiHandler.test.ts @@ -20,19 +20,15 @@ describe(composeServiceApi.name, () => { test('should call transfer handler with resolved config including default config values', async () => { const mockTransferHandler = jest.fn().mockResolvedValue(defaultResponse); - const config = { - ...defaultConfig, - foo: 'bar', - }; const api = composeServiceApi( mockTransferHandler, - input => defaultRequest, - async output => ({ + _ => defaultRequest, + async _ => ({ Result: 'from API', }), defaultConfig, ); - const output = await api({ bar: 'baz', foo: 'foo' }, 'Input'); + await api({ bar: 'baz', foo: 'foo' }, 'Input'); expect(mockTransferHandler).toHaveBeenCalledTimes(1); expect(mockTransferHandler).toHaveBeenCalledWith( defaultRequest, @@ -51,8 +47,8 @@ describe(composeServiceApi.name, () => { }; const api = composeServiceApi( mockTransferHandler, - input => defaultRequest, - async output => ({ + __ => defaultRequest, + async __ => ({ Result: 'from API', }), defaultConfig, @@ -67,7 +63,7 @@ describe(composeServiceApi.name, () => { test('should call serializer and deserializer', async () => { const mockTransferHandler = jest.fn().mockResolvedValue(defaultResponse); - const defaultConfig = { + const defaultConfigWithEndpointResolver = { foo: 'bar', endpointResolver: jest.fn().mockReturnValue('https://a.b'), }; @@ -79,13 +75,13 @@ describe(composeServiceApi.name, () => { mockTransferHandler, mockSerializer, mockDeserializer, - defaultConfig, + defaultConfigWithEndpointResolver, ); - const output = await api({ bar: 'baz', foo: 'foo' }, 'Input'); + await api({ bar: 'baz', foo: 'foo' }, 'Input'); expect(mockSerializer).toHaveBeenCalledTimes(1); expect(mockSerializer).toHaveBeenCalledWith( 'Input', - defaultConfig.endpointResolver.mock.results[0].value, + defaultConfigWithEndpointResolver.endpointResolver.mock.results[0].value, ); expect(mockDeserializer).toHaveBeenCalledTimes(1); expect(mockDeserializer).toHaveBeenCalledWith(defaultResponse); diff --git a/packages/core/__tests__/clients/composeTransferHandler.test.ts b/packages/core/__tests__/clients/composeTransferHandler.test.ts index 6fd3e109945..617beb19b00 100644 --- a/packages/core/__tests__/clients/composeTransferHandler.test.ts +++ b/packages/core/__tests__/clients/composeTransferHandler.test.ts @@ -31,7 +31,7 @@ describe(composeTransferHandler.name, () => { mockFnInOptions(calledFrom: string): void; } const middlewareA: Middleware = - (options: OptionsType) => (next, context) => async request => { + (options: OptionsType) => (next, _) => async request => { request.body += 'A'; options.mockFnInOptions('A'); const resp = await next(request); @@ -40,7 +40,7 @@ describe(composeTransferHandler.name, () => { return resp; }; const middlewareB: Middleware = - (options: OptionsType) => (next, context) => async request => { + (options: OptionsType) => (next, _) => async request => { request.body += 'B'; options.mockFnInOptions('B'); const resp = await next(request); @@ -48,9 +48,11 @@ describe(composeTransferHandler.name, () => { return resp; }; - const coreHandler: TransferHandler = jest - .fn() - .mockResolvedValueOnce({ body: '' } as Response); + const coreHandler: TransferHandler< + Request, + Response, + Record + > = jest.fn().mockResolvedValueOnce({ body: '' } as Response); const handler = composeTransferHandler<[OptionsType, OptionsType]>( coreHandler, [middlewareA, middlewareB], diff --git a/packages/core/__tests__/clients/fetch.test.ts b/packages/core/__tests__/clients/fetch.test.ts index 1ef0e2d8863..694e351c7a7 100644 --- a/packages/core/__tests__/clients/fetch.test.ts +++ b/packages/core/__tests__/clients/fetch.test.ts @@ -23,7 +23,7 @@ describe(fetchTransferHandler.name, () => { const mockFetch = jest.fn(); beforeAll(() => { - global.fetch = mockFetch; + (global as any).fetch = mockFetch; }); beforeEach(() => { @@ -68,8 +68,8 @@ describe(fetchTransferHandler.name, () => { }); it('should support headers', async () => { - mockFetchResponse.headers.forEach.mockImplementation((cb: any) => { - cb('foo', 'bar'); + mockFetchResponse.headers.forEach.mockImplementation((funcParam: any) => { + funcParam('foo', 'bar'); }); const { headers } = await fetchTransferHandler(mockRequest, {}); expect(headers).toEqual({ bar: 'foo' }); diff --git a/packages/core/__tests__/clients/middleware/retry/middleware.test.ts b/packages/core/__tests__/clients/middleware/retry/middleware.test.ts index 34ead22315d..1391f010d23 100644 --- a/packages/core/__tests__/clients/middleware/retry/middleware.test.ts +++ b/packages/core/__tests__/clients/middleware/retry/middleware.test.ts @@ -54,9 +54,9 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { }); const retryableHandler = getRetryableHandler(nextHandler); expect.assertions(2); - let resp; + try { - resp = await retryableHandler(defaultRequest, { + await retryableHandler(defaultRequest, { ...defaultRetryOptions, maxAttempts: 6, }); @@ -94,7 +94,7 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { (resp, error) => error.message !== 'UnretryableError', ); try { - const resp = await retryableHandler(defaultRequest, { + await retryableHandler(defaultRequest, { ...defaultRetryOptions, retryDecider, }); @@ -185,7 +185,7 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { const betweenRetryFunction = jest .fn() .mockRejectedValueOnce(new Error('MiddlewareRetryableError')) - .mockResolvedValue(void 0); + .mockResolvedValue(undefined); const betweenRetryMiddleware = () => (next: any, context: any) => async (args: any) => { await betweenRetryFunction(args, context); @@ -194,7 +194,7 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { }; const doubleRetryableHandler = composeTransferHandler< - [RetryOptions, {}, RetryOptions] + [RetryOptions, Record, RetryOptions] >(coreHandler, [ retryMiddlewareFactory, betweenRetryMiddleware, diff --git a/packages/core/__tests__/singleton/Singleton.test.ts b/packages/core/__tests__/singleton/Singleton.test.ts index 0d0751bfdd9..9726aa0fb87 100644 --- a/packages/core/__tests__/singleton/Singleton.test.ts +++ b/packages/core/__tests__/singleton/Singleton.test.ts @@ -18,7 +18,9 @@ jest.mock('../../src/Hub', () => ({ const mockHubDispatch = Hub.dispatch as jest.Mock; -type ArgumentTypes = F extends (...args: infer A) => any +type ArgumentTypes any> = F extends ( + ...args: infer A +) => any ? A : never; @@ -283,7 +285,7 @@ describe('Session tests', () => { test('fetchAuthSession with credentials provider only', async () => { const mockCredentials = { accessKeyId: 'accessKeyValue', - secretAccessKey: 'secreatAccessKeyValue', + secretAccessKey: 'secretAccessKeyValue', }; Amplify.configure( {}, @@ -295,7 +297,9 @@ describe('Session tests', () => { credentials: mockCredentials, }; }, - clearCredentialsAndIdentityId: () => {}, + clearCredentialsAndIdentityId: () => { + // no-op + }, }, }, }, @@ -361,11 +365,7 @@ describe('Session tests', () => { }; const credentialsSpy = jest.fn( - async ({ - tokens, - authConfig, - identityId, - }): Promise => { + async (_): Promise => { return { credentials: { accessKeyId: 'accessKeyIdValue', @@ -391,7 +391,9 @@ describe('Session tests', () => { Auth: { credentialsProvider: { getCredentialsAndIdentityId: credentialsSpy, - clearCredentialsAndIdentityId: () => {}, + clearCredentialsAndIdentityId: () => { + // no-op + }, }, tokenProvider: { getTokens: spyTokenProvider, @@ -456,11 +458,7 @@ describe('Session tests', () => { }; const credentialsSpy = jest.fn( - async ({ - tokens, - authConfig, - identityId, - }): Promise => { + async (_): Promise => { return { credentials: { accessKeyId: 'accessKeyIdValue', @@ -481,7 +479,9 @@ describe('Session tests', () => { Auth: { credentialsProvider: { getCredentialsAndIdentityId: credentialsSpy, - clearCredentialsAndIdentityId: () => {}, + clearCredentialsAndIdentityId: () => { + // no-op + }, }, tokenProvider: { getTokens: spyTokenProvider, @@ -572,8 +572,7 @@ describe('Session tests', () => { }, ); - const action = async () => - await auth.fetchAuthSession({ forceRefresh: true }); + const action = async () => auth.fetchAuthSession({ forceRefresh: true }); await expect(action()).rejects.toThrow('no no no'); diff --git a/packages/core/__tests__/storage/CookieStorage.test.ts b/packages/core/__tests__/storage/CookieStorage.test.ts index d3093ec7e94..04422d40138 100644 --- a/packages/core/__tests__/storage/CookieStorage.test.ts +++ b/packages/core/__tests__/storage/CookieStorage.test.ts @@ -17,15 +17,18 @@ describe('CookieStorage', () => { const expectedError = 'The sameSite value of cookieStorage must be "lax", "strict" or "none"'; expect(() => { + // eslint-disable-next-line no-new new CookieStorage({ sameSite: undefined }); }).toThrow(expectedError); expect(() => { + // eslint-disable-next-line no-new new CookieStorage({ sameSite: 'foo' as any }); }).toThrow(expectedError); }); it('SameSite value is "none" while secure is false', () => { expect(() => { + // eslint-disable-next-line no-new new CookieStorage({ domain: cookieStorageDomain, secure: false, @@ -63,11 +66,11 @@ describe('CookieStorage', () => { }); it('Clearing cookies should remove all items within the storage', async () => { - const cookieStore = new CookieStorage(cookieStoreData); - await cookieStore.setItem('testKey2', 'testValue'); - const tempReference = await cookieStore.getItem('testKey2'); - await cookieStore.clear(); - expect(await cookieStore.getItem('testKey2')).not.toEqual( + const testCookieStore = new CookieStorage(cookieStoreData); + await testCookieStore.setItem('testKey2', 'testValue'); + const tempReference = await testCookieStore.getItem('testKey2'); + await testCookieStore.clear(); + expect(await testCookieStore.getItem('testKey2')).not.toEqual( tempReference, ); }); diff --git a/packages/core/__tests__/storage/DefaultStorage.test.ts b/packages/core/__tests__/storage/DefaultStorage.test.ts index ca8964f1a5c..8071acb785a 100644 --- a/packages/core/__tests__/storage/DefaultStorage.test.ts +++ b/packages/core/__tests__/storage/DefaultStorage.test.ts @@ -27,6 +27,7 @@ describe('DefaultStorage', () => { it('should not throw if trying to delete a non existing key', async () => { const badKey = 'nonExistingKey'; + // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression await expect(() => { defaultStorage.removeItem(badKey); }).not.toThrow(); diff --git a/packages/core/__tests__/storage/SessionStorage.test.ts b/packages/core/__tests__/storage/SessionStorage.test.ts index 6f35ec0c6ff..df6116d823e 100644 --- a/packages/core/__tests__/storage/SessionStorage.test.ts +++ b/packages/core/__tests__/storage/SessionStorage.test.ts @@ -27,6 +27,7 @@ describe('sessionStorage', () => { it('should not throw if trying to delete a non existing key', async () => { const badKey = 'nonExistingKey'; + // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression await expect(() => { sessionStorage.removeItem(badKey); }).not.toThrow(); diff --git a/packages/core/__tests__/utils.test.ts b/packages/core/__tests__/utils.test.ts index 1968709f609..f81b689842c 100644 --- a/packages/core/__tests__/utils.test.ts +++ b/packages/core/__tests__/utils.test.ts @@ -14,7 +14,9 @@ import { DateUtils } from '../src/Signer/DateUtils'; ConsoleLogger.LOG_LEVEL = 'DEBUG'; describe('Util', () => { - beforeEach(() => {}); + beforeEach(() => { + // no-op + }); describe('DateUtils', () => { test('isClockSkewError', () => { diff --git a/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts b/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts index fe0b5cea7b4..4ca167a5649 100644 --- a/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts +++ b/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts @@ -1,7 +1,7 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { loadBase64, loadGetRandomValues } from '@aws-amplify/react-native'; +import { loadGetRandomValues } from '@aws-amplify/react-native'; import { getAtob, @@ -9,13 +9,11 @@ import { getCrypto, } from '../../../src/utils/globalHelpers/index.native'; -const mockCrypto = { getRandomValues: jest.fn() }; - jest.mock('react-native'); jest.mock('@aws-amplify/react-native', () => ({ loadGetRandomValues: jest.fn(() => { Object.defineProperty(global, 'crypto', { - value: mockCrypto, + value: { getRandomValues: jest.fn(() => 'mocked') }, writable: true, }); }), @@ -26,7 +24,6 @@ jest.mock('@aws-amplify/react-native', () => ({ })); const mockLoadGetRandomValues = loadGetRandomValues as jest.Mock; -const mockLoadBase64 = loadBase64 as jest.Mock; describe('getGlobal (native)', () => { beforeAll(() => { @@ -36,7 +33,7 @@ describe('getGlobal (native)', () => { describe('getCrypto()', () => { it('returns the polyfill crypto from react-native-get-random-values', () => { - expect(getCrypto()).toEqual(mockCrypto); + expect(getCrypto().getRandomValues(null)).toEqual('mocked'); }); }); diff --git a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts index 8dae69b5342..4bae7b803c2 100644 --- a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts +++ b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts @@ -7,7 +7,11 @@ import { createQueuedStorage, keyPrefix, } from '../../../src/utils/queuedStorage/createQueuedStorage.native'; -import { ItemToAdd, QueuedItem } from '../../../src/utils/queuedStorage/types'; +import { + ItemToAdd, + QueuedItem, + QueuedStorage, +} from '../../../src/utils/queuedStorage/types'; import { getAddItemBytesSize } from '../../../src/utils/queuedStorage/getAddItemBytesSize'; jest.mock('@aws-amplify/react-native', () => ({ @@ -31,7 +35,7 @@ describe('createQueuedStorage', () => { const mockTimestamp = new Date('2024-01-02').toUTCString(); describe('initialization', () => { - let queuedStorage; + let queuedStorage: QueuedStorage; const testBytesSize = 1; const mockKeys = [`${keyPrefix}_key1`, `${keyPrefix}_key2`]; const mockQueuedItems = [ @@ -116,30 +120,35 @@ describe('createQueuedStorage', () => { ['peekAll', undefined], ['delete', [{}]], ['clear', undefined], - ])('when invokes %s it throws', async (method, args) => { - const storage = createQueuedStorage(); - await expect(storage[method](args)).rejects.toThrow(expectedError); - }); + ] as unknown as [keyof QueuedStorage, any])( + 'when invokes %s it throws', + async (method: keyof QueuedStorage, args: any) => { + const storage = createQueuedStorage(); + await expect(storage[method](args)).rejects.toThrow(expectedError); + }, + ); }); describe('method add()', () => { - let queuedStorage; - let originalDate; + let queuedStorage: QueuedStorage; + // let originalDate; + let dateNowSpy: jest.SpyInstance; const testInput: ItemToAdd = { content: 'some log content', timestamp: mockTimestamp, }; beforeAll(() => { - originalDate = Date; - Date = { - now: jest.fn(() => 123), - } as any; + // originalDate = Date; + // Date = { + // now: jest.fn(() => 123), + // } as any; + dateNowSpy = jest.spyOn(Date, 'now').mockReturnValue(123); queuedStorage = createQueuedStorage(); }); afterAll(() => { - Date = originalDate; + dateNowSpy.mockRestore(); }); afterEach(() => { @@ -195,7 +204,7 @@ describe('createQueuedStorage', () => { }); describe('method peek() and peekAll()', () => { - let queuedStorage; + let queuedStorage: QueuedStorage; const mockQueuedItems = [ { @@ -283,7 +292,7 @@ describe('createQueuedStorage', () => { }, ]; - let queuedStorage; + let queuedStorage: QueuedStorage; beforeAll(() => { queuedStorage = createQueuedStorage(); @@ -305,7 +314,7 @@ describe('createQueuedStorage', () => { }); describe('method clear()', () => { - let queuedStorage; + let queuedStorage: QueuedStorage; const testAllKeys = [ `${keyPrefix}_key1`, `${keyPrefix}_key2`, diff --git a/packages/core/__tests__/utils/queuedStorage/queuedStorage.test.ts b/packages/core/__tests__/utils/queuedStorage/queuedStorage.test.ts index e8314d82cff..9d3dc822d3c 100644 --- a/packages/core/__tests__/utils/queuedStorage/queuedStorage.test.ts +++ b/packages/core/__tests__/utils/queuedStorage/queuedStorage.test.ts @@ -14,34 +14,64 @@ import { } from '../../../src/utils/queuedStorage/types'; describe('createQueuedStorage', () => { - let originalIndexedDB; - let originalIDBKeyRange; + let originalIndexedDB: IDBFactory; + let originalIDBKeyRange: typeof IDBKeyRange; const mockTimestamp = new Date('2024-01-02').toUTCString(); const mockAdd = jest.fn(() => ({ set onsuccess(handler) { handler(); }, + get onsuccess() { + return () => { + // no op + }; + }, set onerror(handler) { handler(); }, + get onerror() { + return () => { + // no op + }; + }, })); const mockClear = jest.fn(); const mockGetAll = jest.fn(() => ({ set onsuccess(handler) { handler(); }, + get onsuccess() { + return () => { + // no op + }; + }, set onerror(handler) { handler(); }, + get onerror() { + return () => { + // no op + }; + }, result: [] as QueuedItem[], })); const mockDelete = jest.fn(() => ({ set onsuccess(handler) { handler(); }, + get onsuccess() { + return () => { + // no op + }; + }, set onerror(handler) { handler(); }, + get onerror() { + return () => { + // no op + }; + }, })); const mockObjectStore = jest.fn(() => ({ add: mockAdd, @@ -63,10 +93,27 @@ describe('createQueuedStorage', () => { set onupgradeneeded(handler) { handler(); }, + get onupgradeneeded() { + return () => { + // no op + }; + }, set onsuccess(handler) { handler(); }, - set onerror(_) {}, + get onsuccess() { + return () => { + // no op + }; + }, + set onerror(_) { + // no op + }, + get onerror() { + return () => { + // no op + }; + }, result: mockDB, }; const mockIndexedDBOpen = jest.fn(() => mockIndexedDBOpenRequest); @@ -119,7 +166,19 @@ describe('createQueuedStorage', () => { set onsuccess(handler) { handler(); }, - set onerror(_) {}, + get onsuccess() { + return () => { + // no op + }; + }, + set onerror(_) { + // no-op + }, + get onerror() { + return () => { + // no op + }; + }, result: mockQueuedItems, }); queuedStorage = createQueuedStorage(); @@ -172,10 +231,27 @@ describe('createQueuedStorage', () => { set onupgradeneeded(handler) { handler(); }, - set onsuccess(_) {}, + get onupgradeneeded() { + return () => { + // no op + }; + }, + set onsuccess(_) { + // no-op + }, + get onsuccess() { + return () => { + // no op + }; + }, set onerror(handler) { handler(); }, + get onerror() { + return () => { + // no op + }; + }, error: expectedError, result: mockDB, } as any); @@ -187,10 +263,13 @@ describe('createQueuedStorage', () => { ['peekAll', undefined], ['delete', [{}]], ['clear', undefined], - ])('when invokes %s it throws', async (method, args) => { - const storage = createQueuedStorage(); - await expect(storage[method](args)).rejects.toThrow(expectedError); - }); + ] as unknown as [keyof QueuedStorage, any])( + 'when invokes %s it throws', + async (method: keyof QueuedStorage, args: any) => { + const storage = createQueuedStorage(); + await expect(storage[method](args)).rejects.toThrow(expectedError); + }, + ); }); describe('method add()', () => { @@ -231,7 +310,19 @@ describe('createQueuedStorage', () => { set onsuccess(handler) { handler(); }, - set onerror(_) {}, + get onsuccess() { + return () => { + // no op + }; + }, + set onerror(_) { + // no op + }, + get onerror() { + return () => { + // no op + }; + }, result: mockQueuedItems, }); @@ -273,7 +364,19 @@ describe('createQueuedStorage', () => { set onsuccess(handler) { handler(); }, - set onerror(_) {}, + get onsuccess() { + return () => { + // no op + }; + }, + set onerror(_) { + // no-op + }, + get onerror() { + return () => { + // no op + }; + }, result: [mockQueuedItems[0]], }); const result = await queuedStorage.peek(1); @@ -288,7 +391,19 @@ describe('createQueuedStorage', () => { set onsuccess(handler) { handler(); }, - set onerror(_) {}, + get onsuccess() { + return () => { + // no op + }; + }, + set onerror(_) { + // no op + }, + get onerror() { + return () => { + // no op + }; + }, result: mockQueuedItems, });