From dff5b161cf8589a003fc495f3cfeb9bf44d692b6 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 13:02:31 -0700 Subject: [PATCH 01/14] chore(repo): setup the base for lint __tests__ codebase --- .eslintrc.js | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index eb968e3fb61..542c93763e2 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -35,8 +35,25 @@ module.exports = { 'setupTests.ts', 'jest.setup.*', 'jest.config.*', - // temporarily disable lint on __tests__ - '__tests__', + // 'packages/adapter-nextjs/__tests__', + 'packages/analytics/__tests__', + 'packages/api/__tests__', + 'packages/api-graphql/__tests__', + 'packages/api-rest/__tests__', + 'packages/auth/__tests__', + // 'packages/aws-amplify/__tests__', + // 'packages/core/__tests__', + 'packages/datastore/__tests__', + 'packages/datastore-storage-adapter/__tests__', + 'packages/geo/__tests__', + 'packages/interactions/__tests__', + 'packages/notifications/__tests__', + 'packages/predictions/__tests__', + 'packages/pubsub/__tests__', + 'packages/react-native/__tests__', + 'packages/rtn-push-notification/__tests__', + 'packages/rtn-web-browser/__tests__', + 'packages/storage/__tests__', // will enable lint by packages // 'adapter-nextjs', // 'packages/analytics', From 187df13d41a499c203b98ac990d2e975f16277c1 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 13:03:33 -0700 Subject: [PATCH 02/14] chore(adapter-nextjs): run yarn lint:fix --- .../__tests__/api/generateServerClient.test.ts | 5 +++-- .../__tests__/createServerRunner.test.ts | 1 + .../adapter-nextjs/__tests__/mocks/headers.ts | 5 +++-- ...eStorageAdapterFromNextServerContext.test.ts | 17 ++++++++++------- 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts index dfc038de44a..bb002d1f5d7 100644 --- a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts +++ b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts @@ -1,11 +1,12 @@ import { ResourcesConfig } from '@aws-amplify/core'; + import { generateServerClientUsingCookies, generateServerClientUsingReqRes, } from '../../src/api'; import { - getAmplifyConfig, createRunWithAmplifyServerContext, + getAmplifyConfig, } from '../../src/utils'; import { NextApiRequestMock, NextApiResponseMock } from '../mocks/headers'; import { createServerRunnerForAPI } from '../../src/api/createServerRunnerForAPI'; @@ -59,7 +60,7 @@ describe('generateServerClientUsingCookies', () => { }); it('should call createRunWithAmplifyServerContext to create runWithAmplifyServerContext function', async () => { - const cookies = (await headers).cookies; + const { cookies } = await headers; generateServerClientUsingCookies({ config: mockAmplifyConfig, cookies }); expect(mockCreateRunWithAmplifyServerContext).toHaveBeenCalledWith({ diff --git a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts index 17ff383720f..13f8ab7f1bb 100644 --- a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts +++ b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { ResourcesConfig, sharedInMemoryStorage } from '@aws-amplify/core'; + import { NextServer } from '../src/types'; const mockAmplifyConfig: ResourcesConfig = { diff --git a/packages/adapter-nextjs/__tests__/mocks/headers.ts b/packages/adapter-nextjs/__tests__/mocks/headers.ts index 9023b16b0af..f8b5b27be78 100644 --- a/packages/adapter-nextjs/__tests__/mocks/headers.ts +++ b/packages/adapter-nextjs/__tests__/mocks/headers.ts @@ -1,10 +1,11 @@ +import { Socket } from 'net'; +import { IncomingMessage } from 'http'; + import { NextApiRequest, NextApiResponse } from 'next/index.js'; import { NextApiRequestCookies, NextApiRequestQuery, } from 'next/dist/server/api-utils/index.js'; -import { Socket } from 'net'; -import { IncomingMessage } from 'http'; export type NextApiRequestOptions = Partial; export class NextApiRequestMock diff --git a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts index 857c0369514..0023fb7aa80 100644 --- a/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts +++ b/packages/adapter-nextjs/__tests__/utils/createCookieStorageAdapterFromNextServerContext.test.ts @@ -1,18 +1,21 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 +import { IncomingMessage, ServerResponse } from 'http'; +import { Socket } from 'net'; + import { enableFetchMocks } from 'jest-fetch-mock'; +import { NextRequest, NextResponse } from 'next/server.js'; +import { cookies } from 'next/headers.js'; + +import { + DATE_IN_THE_PAST, + createCookieStorageAdapterFromNextServerContext, +} from '../../src/utils/createCookieStorageAdapterFromNextServerContext'; // Make global Request available during test enableFetchMocks(); -import { NextRequest, NextResponse } from 'next/server.js'; -import { cookies } from 'next/headers.js'; -import { createCookieStorageAdapterFromNextServerContext } from '../../src/utils/createCookieStorageAdapterFromNextServerContext'; -import { DATE_IN_THE_PAST } from '../../src/utils/createCookieStorageAdapterFromNextServerContext'; -import { IncomingMessage, ServerResponse } from 'http'; -import { Socket } from 'net'; - jest.mock('next/headers', () => ({ cookies: jest.fn(), })); From 766073fd5ca37cef35d0b89f9ef013f1931ff960 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 13:05:05 -0700 Subject: [PATCH 03/14] chore(adapter-nextjs): manual fix linter reported erros --- .../__tests__/api/generateServerClient.test.ts | 4 +++- .../adapter-nextjs/__tests__/createServerRunner.test.ts | 8 ++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts index bb002d1f5d7..caed424502a 100644 --- a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts +++ b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts @@ -95,7 +95,9 @@ describe('generateServerClient', () => { })); jest.mock('@aws-amplify/core/internals/adapter-core', () => ({ - getAmplifyServerContext: () => {}, + getAmplifyServerContext: () => { + // no-op for testing + }, })); const client = generateServerClientUsingReqRes({ diff --git a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts index 13f8ab7f1bb..678d1fbf42c 100644 --- a/packages/adapter-nextjs/__tests__/createServerRunner.test.ts +++ b/packages/adapter-nextjs/__tests__/createServerRunner.test.ts @@ -51,7 +51,7 @@ describe('createServerRunner', () => { parseAWSExports: mockParseAWSExports, })); - createServerRunner = require('../src').createServerRunner; + ({ createServerRunner } = require('../src')); }); afterEach(() => { @@ -77,7 +77,7 @@ describe('createServerRunner', () => { describe('runWithAmplifyServerContext', () => { describe('when amplifyConfig.Auth is not defined', () => { it('should call runWithAmplifyServerContextCore without Auth library options', () => { - const mockAmplifyConfig: ResourcesConfig = { + const mockAmplifyConfigWithoutAuth: ResourcesConfig = { Analytics: { Pinpoint: { appId: 'app-id', @@ -86,12 +86,12 @@ describe('createServerRunner', () => { }, }; const { runWithAmplifyServerContext } = createServerRunner({ - config: mockAmplifyConfig, + config: mockAmplifyConfigWithoutAuth, }); const operation = jest.fn(); runWithAmplifyServerContext({ operation, nextServerContext: null }); expect(mockRunWithAmplifyServerContextCore).toHaveBeenCalledWith( - mockAmplifyConfig, + mockAmplifyConfigWithoutAuth, {}, operation, ); From d66a58e9e9a6478d12eac47ba4095dbffcbcd99b Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 13:11:45 -0700 Subject: [PATCH 04/14] chore(aws-amplify): run yarn lint:fix Please enter the commit message for your changes. Lines starting --- .../createAWSCredentialsAndIdentityIdProvider.test.ts | 7 ++----- .../cognito/createUserPoolsTokenProvider.test.ts | 2 +- .../adapterCore/runWithAmplifyServerContext.test.ts | 3 ++- packages/aws-amplify/__tests__/initSingleton.test.ts | 4 ++-- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts index 92f291e5bd4..9df53b6f2b8 100644 --- a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createAWSCredentialsAndIdentityIdProvider.test.ts @@ -5,11 +5,8 @@ import { CognitoAWSCredentialsAndIdentityIdProvider, DefaultIdentityIdStore, } from '@aws-amplify/auth/cognito'; -import { - CredentialsAndIdentityIdProvider, - AuthConfig, - KeyValueStorageInterface, -} from '@aws-amplify/core'; +import { AuthConfig, KeyValueStorageInterface } from '@aws-amplify/core'; + import { createAWSCredentialsAndIdentityIdProvider } from '../../../../src/adapter-core'; jest.mock('@aws-amplify/auth/cognito'); diff --git a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts index 2fec2bc5f06..0bea27d44fb 100644 --- a/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/authProvidersFactories/cognito/createUserPoolsTokenProvider.test.ts @@ -6,8 +6,8 @@ import { TokenOrchestrator, refreshAuthTokens, } from '@aws-amplify/auth/cognito'; - import { AuthConfig, KeyValueStorageInterface } from '@aws-amplify/core'; + import { createUserPoolsTokenProvider } from '../../../../src/adapter-core'; jest.mock('@aws-amplify/auth/cognito'); diff --git a/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts b/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts index 8299cce6224..9e2655bd2d5 100644 --- a/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts +++ b/packages/aws-amplify/__tests__/adapterCore/runWithAmplifyServerContext.test.ts @@ -1,12 +1,13 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { runWithAmplifyServerContext } from '../../src/adapter-core'; import { createAmplifyServerContext, destroyAmplifyServerContext, } from '@aws-amplify/core/internals/adapter-core'; +import { runWithAmplifyServerContext } from '../../src/adapter-core'; + // mock serverContext jest.mock('@aws-amplify/core/internals/adapter-core'); const mockCreateAmplifyServerContext = createAmplifyServerContext as jest.Mock; diff --git a/packages/aws-amplify/__tests__/initSingleton.test.ts b/packages/aws-amplify/__tests__/initSingleton.test.ts index dec181ca74a..2aa93209569 100644 --- a/packages/aws-amplify/__tests__/initSingleton.test.ts +++ b/packages/aws-amplify/__tests__/initSingleton.test.ts @@ -7,11 +7,11 @@ import { ResourcesConfig, defaultStorage, } from '@aws-amplify/core'; + import { - cognitoUserPoolsTokenProvider, cognitoCredentialsProvider, + cognitoUserPoolsTokenProvider, } from '../src/auth/cognito'; - import { Amplify } from '../src'; jest.mock('@aws-amplify/core'); From c70bae3154f49b25ada2f5f18d51c689fe6f97dc Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 13:18:02 -0700 Subject: [PATCH 05/14] chore(aws-amplify): add camelcase var name exception: phone_number --- .eslintrc.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.eslintrc.js b/.eslintrc.js index 542c93763e2..fe412087332 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -80,6 +80,9 @@ module.exports = { 'error', { allow: [ + // exceptions for core package + 'phone_number', + // exceptions for api packages 'graphql_headers', // exceptions for the legacy config /^(aws_|amazon_)/, From f899b97b213113534b037f89611e1142f3000168 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 13:18:58 -0700 Subject: [PATCH 06/14] chore(core): run yarn lint:fix --- .../BackgroundProcessManager.test.ts | 16 ++++++++--- .../__tests__/Cache/utils/cacheUtils.test.ts | 2 +- packages/core/__tests__/ConsoleLogger.test.ts | 4 +-- packages/core/__tests__/Hub.test.ts | 2 +- .../core/__tests__/JS-browser-runtime.test.ts | 4 +-- packages/core/__tests__/Mutex.test.ts | 28 +++++++++++++------ .../Platform/customUserAgent.test.ts | 4 +-- .../core/__tests__/Platform/userAgent.test.ts | 13 +++------ packages/core/__tests__/Retry.test.ts | 6 ++-- packages/core/__tests__/ServiceWorker.test.ts | 12 ++++---- packages/core/__tests__/Signer.test.ts | 3 ++ packages/core/__tests__/StringUtils.test.ts | 4 ++- .../adapterCore/serverContext.test.ts | 2 +- .../getCredentialsForIdentity.test.ts | 2 +- .../awsClients/cognitoIdentity/getId.test.ts | 2 +- .../pinpoint/getInAppMessages.test.ts | 2 +- .../awsClients/pinpoint/putEvents.test.ts | 2 +- .../pinpoint/updateEndpoint.test.ts | 2 +- .../__tests__/awsClients/testUtils/data.ts | 1 + .../clients/composeTransferHandler.test.ts | 10 +++++-- packages/core/__tests__/clients/fetch.test.ts | 4 +-- .../middleware/retry/middleware.test.ts | 9 ++++-- .../middleware/signing/middleware.test.ts | 3 +- .../signer/signatureV4/presignUrl.test.ts | 6 ++-- .../signer/signatureV4/signRequest.test.ts | 6 ++-- .../signatureV4/testUtils/signingTestTable.ts | 1 + .../signatureV4/utils/getSignature.test.ts | 2 +- .../core/__tests__/parseAWSExports.test.ts | 2 +- .../pinpoint/apis/flushEvents.test.ts | 2 +- .../providers/pinpoint/apis/record.test.ts | 5 ++-- .../testUtils/getExpectedPutEventsInput.ts | 2 +- .../pinpoint/apis/updateEndpoint.test.ts | 2 ++ .../__tests__/singleton/Singleton.test.ts | 9 ++++-- .../__tests__/storage/CookieStorage.test.ts | 2 +- packages/core/__tests__/utils.test.ts | 2 +- .../utils/generateRandomString.test.ts | 1 + .../globalHelpers.native.test.ts | 5 ++-- .../queuedStorage.native.test.ts | 1 + 38 files changed, 116 insertions(+), 69 deletions(-) diff --git a/packages/core/__tests__/BackgroundProcessManager.test.ts b/packages/core/__tests__/BackgroundProcessManager.test.ts index c06cccc6d46..71f893d56f5 100644 --- a/packages/core/__tests__/BackgroundProcessManager.test.ts +++ b/packages/core/__tests__/BackgroundProcessManager.test.ts @@ -1,4 +1,5 @@ import { Observable } from 'rxjs'; + import { BackgroundProcessManager } from '../src/BackgroundProcessManager'; import { BackgroundProcessManagerState } from '../src/BackgroundProcessManager/types'; @@ -287,7 +288,7 @@ describe('BackgroundProcessManager', () => { test('can send termination signals to jobs that support termination, with reject', async () => { let completed = false; - let thrown = undefined; + let thrown; const manager = new BackgroundProcessManager(); const resultPromise = manager.add(async onTerminate => { @@ -383,7 +384,9 @@ describe('BackgroundProcessManager', () => { // that the observable constructor can manage it like a hook. new Observable(observer => { const { resolve, onTerminate } = manager.add(); - const interval = setInterval(() => observer.next({}), 10); + const interval = setInterval(() => { + observer.next({}); + }, 10); const unsubscribe = () => { resolve(); // always remember to resolve/reject! @@ -392,6 +395,7 @@ describe('BackgroundProcessManager', () => { }; onTerminate.then(unsubscribe); + return unsubscribe; }).subscribe(() => count++); @@ -415,7 +419,9 @@ describe('BackgroundProcessManager', () => { let count = 0; const subscription = new Observable(observer => { - const interval = setInterval(() => observer.next({}), 10); + const interval = setInterval(() => { + observer.next({}); + }, 10); // LOOK: here's the magic. (tada!) return manager.addCleaner(async () => { @@ -443,7 +449,9 @@ describe('BackgroundProcessManager', () => { let count = 0; const subscription = new Observable(observer => { - const interval = setInterval(() => observer.next({}), 10); + const interval = setInterval(() => { + observer.next({}); + }, 10); // LOOK: here's the magic. (tada!) return manager.addCleaner(async () => { diff --git a/packages/core/__tests__/Cache/utils/cacheUtils.test.ts b/packages/core/__tests__/Cache/utils/cacheUtils.test.ts index 4c99645a352..ad46e477d52 100644 --- a/packages/core/__tests__/Cache/utils/cacheUtils.test.ts +++ b/packages/core/__tests__/Cache/utils/cacheUtils.test.ts @@ -3,7 +3,7 @@ import { getByteLength } from '../../../src/Cache/utils/cacheHelpers'; describe('cacheHelpers', () => { describe('getByteLength()', () => { test('happy case', () => { - const str: string = 'abc'; + const str = 'abc'; expect(getByteLength(str)).toBe(3); const str2: string = String.fromCharCode(0x80); diff --git a/packages/core/__tests__/ConsoleLogger.test.ts b/packages/core/__tests__/ConsoleLogger.test.ts index 069fed59ca1..9bc7738947a 100644 --- a/packages/core/__tests__/ConsoleLogger.test.ts +++ b/packages/core/__tests__/ConsoleLogger.test.ts @@ -16,7 +16,7 @@ describe('ConsoleLogger', () => { }); describe('pluggables', () => { - /*it('should store pluggables correctly when addPluggable is called', () => { + /* it('should store pluggables correctly when addPluggable is called', () => { const provider = new AWSCloudWatchProvider(); const logger = new Logger('name'); logger.addPluggable(provider); @@ -26,7 +26,7 @@ describe('ConsoleLogger', () => { expect(pluggables[0].getProviderName()).toEqual( AWS_CLOUDWATCH_PROVIDER_NAME ); - });*/ + }); */ it('should do nothing when no plugin is provided to addPluggable', () => { const logger = new ConsoleLogger('name'); diff --git a/packages/core/__tests__/Hub.test.ts b/packages/core/__tests__/Hub.test.ts index 141ebbed16f..216730b5254 100644 --- a/packages/core/__tests__/Hub.test.ts +++ b/packages/core/__tests__/Hub.test.ts @@ -1,4 +1,4 @@ -import { Hub, AMPLIFY_SYMBOL } from '../src/Hub'; +import { Hub } from '../src/Hub'; import { ConsoleLogger } from '../src'; describe('Hub', () => { diff --git a/packages/core/__tests__/JS-browser-runtime.test.ts b/packages/core/__tests__/JS-browser-runtime.test.ts index 7050481bb5c..372b902f10c 100644 --- a/packages/core/__tests__/JS-browser-runtime.test.ts +++ b/packages/core/__tests__/JS-browser-runtime.test.ts @@ -9,12 +9,12 @@ describe('isBrowser build test', () => { // testing the Node.js process. const originalVersions = process.versions; beforeEach(() => { - //@ts-ignore + // @ts-ignore delete global.process.versions; }); afterEach(() => { - //@ts-ignore + // @ts-ignore global.process.versions = originalVersions; }); diff --git a/packages/core/__tests__/Mutex.test.ts b/packages/core/__tests__/Mutex.test.ts index e7335f292e5..6a47360a6a8 100644 --- a/packages/core/__tests__/Mutex.test.ts +++ b/packages/core/__tests__/Mutex.test.ts @@ -49,13 +49,17 @@ describe('Mutex', function () { test('runExclusive passes result (immediate)', function () { return mutex .runExclusive(() => 10) - .then(value => expect(value).toBe(10)); + .then(value => { + expect(value).toBe(10); + }); }); test('runExclusive passes result (promise)', function () { return mutex .runExclusive(() => Promise.resolve(10)) - .then(value => expect(value).toBe(10)); + .then(value => { + expect(value).toBe(10); + }); }); test('runExclusive passes rejection', function () { @@ -63,7 +67,9 @@ describe('Mutex', function () { .runExclusive(() => Promise.reject('foo')) .then( () => Promise.reject('should have been rejected'), - value => expect(value).toBe('foo'), + value => { + expect(value).toBe('foo'); + }, ); }); @@ -74,7 +80,9 @@ describe('Mutex', function () { }) .then( () => Promise.reject('should have been rejected'), - value => expect(value).toBe('foo'), + value => { + expect(value).toBe('foo'); + }, ); }); @@ -91,7 +99,9 @@ describe('Mutex', function () { ), ); - return mutex.runExclusive(() => expect(flag).toBe(true)); + return mutex.runExclusive(() => { + expect(flag).toBe(true); + }); }); test('exceptions during runExclusive do not leave mutex locked', function () { @@ -107,7 +117,9 @@ describe('Mutex', function () { () => undefined, ); - return mutex.runExclusive(() => expect(flag).toBe(true)); + return mutex.runExclusive(() => { + expect(flag).toBe(true); + }); }); test('new mutex is unlocked', function () { @@ -115,8 +127,8 @@ describe('Mutex', function () { }); test('isLocked reflects the mutex state', async function () { - const lock1 = mutex.acquire(), - lock2 = mutex.acquire(); + const lock1 = mutex.acquire(); + const lock2 = mutex.acquire(); expect(mutex.isLocked()).toBe(true); diff --git a/packages/core/__tests__/Platform/customUserAgent.test.ts b/packages/core/__tests__/Platform/customUserAgent.test.ts index 6ce8a3a2684..707f1faf227 100644 --- a/packages/core/__tests__/Platform/customUserAgent.test.ts +++ b/packages/core/__tests__/Platform/customUserAgent.test.ts @@ -1,8 +1,8 @@ import { - Category, AuthAction, - StorageAction, + Category, SetCustomUserAgentInput, + StorageAction, } from '../../src/Platform/types'; const MOCK_AUTH_UA_STATE: SetCustomUserAgentInput = { diff --git a/packages/core/__tests__/Platform/userAgent.test.ts b/packages/core/__tests__/Platform/userAgent.test.ts index 88174e3d75f..383b92486f0 100644 --- a/packages/core/__tests__/Platform/userAgent.test.ts +++ b/packages/core/__tests__/Platform/userAgent.test.ts @@ -1,18 +1,13 @@ import { - getAmplifyUserAgentObject, - getAmplifyUserAgent, Platform, + getAmplifyUserAgent, + getAmplifyUserAgentObject, } from '../../src/Platform'; import { version } from '../../src/Platform/version'; +import { AuthAction, Category, Framework } from '../../src/Platform/types'; import { - ApiAction, - AuthAction, - Category, - Framework, -} from '../../src/Platform/types'; -import { - detectFramework, clearCache, + detectFramework, } from '../../src/Platform/detectFramework'; import * as detection from '../../src/Platform/detection'; import { getCustomUserAgent } from '../../src/Platform/customUserAgent'; diff --git a/packages/core/__tests__/Retry.test.ts b/packages/core/__tests__/Retry.test.ts index a7389237985..561865b7bc7 100644 --- a/packages/core/__tests__/Retry.test.ts +++ b/packages/core/__tests__/Retry.test.ts @@ -1,7 +1,7 @@ import { - retry, - jitteredExponentialRetry, NonRetryableError, + jitteredExponentialRetry, + retry, } from '../src/utils/retry'; import { BackgroundProcessManager } from '../src/BackgroundProcessManager'; @@ -63,6 +63,7 @@ describe('retry', () => { function delayFunction(attempt, args) { receivedAttempt = attempt; receivedArgs = args; + return 1; } @@ -83,6 +84,7 @@ describe('retry', () => { return false; } count++; + return 1; } diff --git a/packages/core/__tests__/ServiceWorker.test.ts b/packages/core/__tests__/ServiceWorker.test.ts index f63e07aeed5..0e575ed5293 100644 --- a/packages/core/__tests__/ServiceWorker.test.ts +++ b/packages/core/__tests__/ServiceWorker.test.ts @@ -17,7 +17,7 @@ describe('ServiceWorker test', () => { serviceWorker.enablePush('publicKey'); }; - return expect(enablePush).toThrow(AmplifyError); + expect(enablePush).toThrow(AmplifyError); }); test('fails when registering', async () => { (global as any).navigator.serviceWorker = { @@ -62,7 +62,7 @@ describe('ServiceWorker test', () => { const serviceWorker = new ServiceWorker(); await serviceWorker.register(); - return expect(bla[status].addEventListener).toHaveBeenCalledTimes(2); + expect(bla[status].addEventListener).toHaveBeenCalledTimes(2); }); }); }); @@ -80,7 +80,7 @@ describe('ServiceWorker test', () => { serviceWorker.send('A message'); - return expect(bla.installing.postMessage).toHaveBeenCalledTimes(0); + expect(bla.installing.postMessage).toHaveBeenCalledTimes(0); }); test('can send string message after registration', async () => { const bla = { @@ -96,9 +96,7 @@ describe('ServiceWorker test', () => { serviceWorker.send('A message'); - return expect(bla.installing.postMessage).toHaveBeenCalledWith( - 'A message', - ); + expect(bla.installing.postMessage).toHaveBeenCalledWith('A message'); }); test('can send object message after registration', async () => { const bla = { @@ -114,7 +112,7 @@ describe('ServiceWorker test', () => { serviceWorker.send({ property: 'value' }); - return expect(bla.installing.postMessage).toHaveBeenCalledWith( + expect(bla.installing.postMessage).toHaveBeenCalledWith( JSON.stringify({ property: 'value' }), ); }); diff --git a/packages/core/__tests__/Signer.test.ts b/packages/core/__tests__/Signer.test.ts index 4e15f008282..9453703c2ca 100644 --- a/packages/core/__tests__/Signer.test.ts +++ b/packages/core/__tests__/Signer.test.ts @@ -5,6 +5,7 @@ import { SignRequestOptions } from '../src/clients/middleware/signing/signer/sig import { Signer } from '../src/Signer'; import { DateUtils } from '../src/Signer/DateUtils'; import * as getSignatureModule from '../src/clients/middleware/signing/signer/signatureV4/utils/getSignature'; + import { credentials, credentialsWithToken, @@ -39,6 +40,7 @@ describe('Signer.sign', () => { ...signingOptions, ...options, }; + return [name, updatedRequest, updatedOptions, expectedAuthorization]; }, ), @@ -146,6 +148,7 @@ describe('Signer.signUrl', () => { ...signingOptions, ...options, }; + return [name, updatedRequest, updatedOptions, expectedUrl]; }, ), diff --git a/packages/core/__tests__/StringUtils.test.ts b/packages/core/__tests__/StringUtils.test.ts index 8fa74b7236d..e8bfaabff98 100644 --- a/packages/core/__tests__/StringUtils.test.ts +++ b/packages/core/__tests__/StringUtils.test.ts @@ -1,5 +1,7 @@ -import { urlSafeEncode, urlSafeDecode } from '../src/utils'; import { TextDecoder, TextEncoder } from 'util'; + +import { urlSafeDecode, urlSafeEncode } from '../src/utils'; + (global as any).TextEncoder = TextEncoder; (global as any).TextDecoder = TextDecoder; diff --git a/packages/core/__tests__/adapterCore/serverContext.test.ts b/packages/core/__tests__/adapterCore/serverContext.test.ts index ea6e2a55f1b..3f401e38aa2 100644 --- a/packages/core/__tests__/adapterCore/serverContext.test.ts +++ b/packages/core/__tests__/adapterCore/serverContext.test.ts @@ -3,8 +3,8 @@ import { createAmplifyServerContext, - getAmplifyServerContext, destroyAmplifyServerContext, + getAmplifyServerContext, } from '../../src/adapterCore'; const mockConfigure = jest.fn(); diff --git a/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts b/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts index 8125a212b7d..e7f820549e2 100644 --- a/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts +++ b/packages/core/__tests__/awsClients/cognitoIdentity/getCredentialsForIdentity.test.ts @@ -1,8 +1,8 @@ import { fetchTransferHandler } from '../../../src/clients/handlers/fetch'; import { - getCredentialsForIdentity, GetCredentialsForIdentityInput, GetCredentialsForIdentityOutput, + getCredentialsForIdentity, } from '../../../src/awsClients/cognitoIdentity'; import { cognitoIdentityHandlerOptions, diff --git a/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts b/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts index 4268cb73fe3..fceb0508ad7 100644 --- a/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts +++ b/packages/core/__tests__/awsClients/cognitoIdentity/getId.test.ts @@ -1,8 +1,8 @@ import { fetchTransferHandler } from '../../../src/clients/handlers/fetch'; import { - getId, GetIdInput, GetIdOutput, + getId, } from '../../../src/awsClients/cognitoIdentity'; import { cognitoIdentityHandlerOptions, diff --git a/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts b/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts index 826254af149..9bebbf61c03 100644 --- a/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts +++ b/packages/core/__tests__/awsClients/pinpoint/getInAppMessages.test.ts @@ -3,9 +3,9 @@ import { fetchTransferHandler } from '../../../src/clients/handlers/fetch'; import { - getInAppMessages, GetInAppMessagesInput, GetInAppMessagesOutput, + getInAppMessages, } from '../../../src/awsClients/pinpoint'; import { mockApplicationId, diff --git a/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts b/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts index f39335eaf60..192a1d6af1e 100644 --- a/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts +++ b/packages/core/__tests__/awsClients/pinpoint/putEvents.test.ts @@ -3,9 +3,9 @@ import { fetchTransferHandler } from '../../../src/clients/handlers/fetch'; import { - putEvents, PutEventsInput, PutEventsOutput, + putEvents, } from '../../../src/awsClients/pinpoint'; import { mockApplicationId, diff --git a/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts b/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts index 3927c202a27..99eaed5fdc8 100644 --- a/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts +++ b/packages/core/__tests__/awsClients/pinpoint/updateEndpoint.test.ts @@ -3,9 +3,9 @@ import { fetchTransferHandler } from '../../../src/clients/handlers/fetch'; import { - updateEndpoint, UpdateEndpointInput, UpdateEndpointOutput, + updateEndpoint, } from '../../../src/awsClients/pinpoint'; import { mockApplicationId, diff --git a/packages/core/__tests__/awsClients/testUtils/data.ts b/packages/core/__tests__/awsClients/testUtils/data.ts index 9227c964aac..6d107c9e660 100644 --- a/packages/core/__tests__/awsClients/testUtils/data.ts +++ b/packages/core/__tests__/awsClients/testUtils/data.ts @@ -20,6 +20,7 @@ export const mockJsonResponse = ({ blob: async () => fail('blob() should not be called'), text: async () => fail('text() should not be called'), } as HttpResponse['body']; + return { statusCode: status, headers, diff --git a/packages/core/__tests__/clients/composeTransferHandler.test.ts b/packages/core/__tests__/clients/composeTransferHandler.test.ts index de7976c339d..6fd3e109945 100644 --- a/packages/core/__tests__/clients/composeTransferHandler.test.ts +++ b/packages/core/__tests__/clients/composeTransferHandler.test.ts @@ -11,7 +11,9 @@ import { describe(composeTransferHandler.name, () => { test('should call core handler', async () => { - type HandlerOptions = { foo: string }; + interface HandlerOptions { + foo: string; + } const coreHandler: TransferHandler = jest .fn() .mockResolvedValue({ body: 'Response' } as Response); @@ -25,13 +27,16 @@ describe(composeTransferHandler.name, () => { }); test('should call execute middleware in order', async () => { - type OptionsType = { mockFnInOptions: (calledFrom: string) => void }; + interface OptionsType { + mockFnInOptions(calledFrom: string): void; + } const middlewareA: Middleware = (options: OptionsType) => (next, context) => async request => { request.body += 'A'; options.mockFnInOptions('A'); const resp = await next(request); resp.body += 'A'; + return resp; }; const middlewareB: Middleware = @@ -40,6 +45,7 @@ describe(composeTransferHandler.name, () => { options.mockFnInOptions('B'); const resp = await next(request); resp.body += 'B'; + return resp; }; const coreHandler: TransferHandler = jest diff --git a/packages/core/__tests__/clients/fetch.test.ts b/packages/core/__tests__/clients/fetch.test.ts index db72190c826..1ef0e2d8863 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.fetch = mockFetch; }); beforeEach(() => { @@ -32,7 +32,7 @@ describe(fetchTransferHandler.name, () => { }); it('should support abort signal', async () => { - const signal = new AbortController().signal; + const { signal } = new AbortController(); await fetchTransferHandler(mockRequest, { abortSignal: signal }); expect(mockFetch).toHaveBeenCalledTimes(1); expect(mockFetch.mock.calls[0][1]).toEqual( diff --git a/packages/core/__tests__/clients/middleware/retry/middleware.test.ts b/packages/core/__tests__/clients/middleware/retry/middleware.test.ts index f17c422d37b..34ead22315d 100644 --- a/packages/core/__tests__/clients/middleware/retry/middleware.test.ts +++ b/packages/core/__tests__/clients/middleware/retry/middleware.test.ts @@ -4,8 +4,8 @@ import { HttpResponse, MiddlewareHandler } from '../../../../src/clients/types'; import { composeTransferHandler } from '../../../../src/clients/internal/composeTransferHandler'; import { - retryMiddlewareFactory, RetryOptions, + retryMiddlewareFactory, } from '../../../../src/clients/middleware/retry'; jest.spyOn(global, 'setTimeout'); @@ -155,8 +155,11 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { const retryDecider = async () => true; const computeDelay = jest.fn().mockImplementation(attempt => { if (attempt === 1) { - setTimeout(() => controller.abort(), 100); + setTimeout(() => { + controller.abort(); + }, 100); } + return 200; }); try { @@ -186,6 +189,7 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { const betweenRetryMiddleware = () => (next: any, context: any) => async (args: any) => { await betweenRetryFunction(args, context); + return next(args); }; @@ -201,6 +205,7 @@ describe(`${retryMiddlewareFactory.name} middleware`, () => { .fn() .mockImplementation((response, error: Error) => { if (error && error.message.endsWith('RetryableError')) return true; + return false; }); const computeDelay = jest.fn().mockReturnValue(0); diff --git a/packages/core/__tests__/clients/middleware/signing/middleware.test.ts b/packages/core/__tests__/clients/middleware/signing/middleware.test.ts index 6c481ecc34c..a3183ebcdb5 100644 --- a/packages/core/__tests__/clients/middleware/signing/middleware.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/middleware.test.ts @@ -3,8 +3,8 @@ import { composeTransferHandler } from '../../../../src/clients/internal/composeTransferHandler'; import { - signingMiddlewareFactory, SigningOptions, + signingMiddlewareFactory, } from '../../../../src/clients/middleware/signing'; import { getSkewCorrectedDate } from '../../../../src/clients/middleware/signing/utils/getSkewCorrectedDate'; import { getUpdatedSystemClockOffset } from '../../../../src/clients/middleware/signing/utils/getUpdatedSystemClockOffset'; @@ -13,6 +13,7 @@ import { HttpResponse, MiddlewareHandler, } from '../../../../src/clients/types'; + import { credentials, signingDate, diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts index c27b1bdb6a8..279fc50beea 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/presignUrl.test.ts @@ -3,14 +3,15 @@ import { presignUrl } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/presignUrl'; import { HttpRequest } from '../../../../../../src/clients/types'; +import { PresignUrlOptions } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/types'; +import { getSignature } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature'; + import { signingTestTable } from './testUtils/signingTestTable'; import { formattedDates, getDefaultRequest, signingOptions, } from './testUtils/data'; -import { PresignUrlOptions } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/types'; -import { getSignature } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature'; jest.mock( '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature', @@ -40,6 +41,7 @@ describe('presignUrl', () => { ...signingOptions, ...options, }; + return [name, updatedRequest, updatedOptions, expectedUrl]; }, ), diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts index 857f56a310b..ef8089b6aea 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/signRequest.test.ts @@ -3,14 +3,15 @@ import { signRequest } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/signRequest'; import { HttpRequest } from '../../../../../../src/clients/types'; +import { SignRequestOptions } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/types'; +import { getSignature } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature'; + import { signingTestTable } from './testUtils/signingTestTable'; import { formattedDates, getDefaultRequest, signingOptions, } from './testUtils/data'; -import { SignRequestOptions } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/types'; -import { getSignature } from '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature'; jest.mock( '../../../../../../src/clients/middleware/signing/signer/signatureV4/utils/getSignature', @@ -40,6 +41,7 @@ describe('signRequest', () => { ...signingOptions, ...options, }; + return [name, updatedRequest, updatedOptions, expectedAuthorization]; }, ), diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts index 575ce159b21..37ff662abd2 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/testUtils/signingTestTable.ts @@ -3,6 +3,7 @@ import { SignRequestOptions } from '../../../../../../../src/clients/middleware/signing/signer/signatureV4/types'; import { HttpRequest } from '../../../../../../../src/clients/types'; + import { credentialsWithToken, signingOptions, url } from './data'; interface TestCase { diff --git a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts index 1a796e7bd2e..8ccc5e5283e 100644 --- a/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts +++ b/packages/core/__tests__/clients/middleware/signing/signer/signatureV4/utils/getSignature.test.ts @@ -2,8 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import { - credentials, credentialScope, + credentials, formattedDates, getDefaultRequest, signingRegion, diff --git a/packages/core/__tests__/parseAWSExports.test.ts b/packages/core/__tests__/parseAWSExports.test.ts index a194ef25528..4e26fc34b2d 100644 --- a/packages/core/__tests__/parseAWSExports.test.ts +++ b/packages/core/__tests__/parseAWSExports.test.ts @@ -243,7 +243,7 @@ describe('parseAWSExports', () => { signUpVerificationMethod: undefined, userAttributes: {}, userPoolClientId: undefined, - userPoolId: userPoolId, + userPoolId, }, }, }); diff --git a/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts b/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts index 367773b2be0..242389e0090 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/flushEvents.test.ts @@ -3,7 +3,7 @@ import { getEventBuffer } from '../../../../src/providers/pinpoint/utils/getEventBuffer'; import { flushEvents } from '../../../../src/providers/pinpoint'; -import { appId, region, credentials, identityId } from '../testUtils/data'; +import { appId, credentials, identityId, region } from '../testUtils/data'; import { BUFFER_SIZE, FLUSH_INTERVAL, diff --git a/packages/core/__tests__/providers/pinpoint/apis/record.test.ts b/packages/core/__tests__/providers/pinpoint/apis/record.test.ts index fc17952a8c8..0767effeee1 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/record.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/record.test.ts @@ -1,4 +1,5 @@ import { v4 } from 'uuid'; + import { putEvents as clientPutEvents } from '../../../../src/awsClients/pinpoint'; import { record } from '../../../../src/providers/pinpoint/apis'; import { updateEndpoint } from '../../../../src/providers/pinpoint/apis/updateEndpoint'; @@ -8,9 +9,9 @@ import { category, credentials, endpointId, - region, - identityId, event, + identityId, + region, uuid, } from '../testUtils/data'; import { getEventBuffer } from '../../../../src/providers/pinpoint/utils/getEventBuffer'; diff --git a/packages/core/__tests__/providers/pinpoint/apis/testUtils/getExpectedPutEventsInput.ts b/packages/core/__tests__/providers/pinpoint/apis/testUtils/getExpectedPutEventsInput.ts index 0101631ce78..ee7ce356a60 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/testUtils/getExpectedPutEventsInput.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/testUtils/getExpectedPutEventsInput.ts @@ -4,8 +4,8 @@ import { appId, endpointId as defaultEndpointId, - uuid, event as defaultEvent, + uuid, } from '../../testUtils/data'; export const getExpectedPutEventsInput = ({ diff --git a/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts b/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts index 5fa35dd912b..6ad4e718955 100644 --- a/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts +++ b/packages/core/__tests__/providers/pinpoint/apis/updateEndpoint.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { v4 } from 'uuid'; + import { getClientInfo } from '../../../../src/utils/getClientInfo'; import { updateEndpoint as clientUpdateEndpoint } from '../../../../src/awsClients/pinpoint'; import { cacheEndpointId } from '../../../../src/providers/pinpoint/utils/cacheEndpointId'; @@ -18,6 +19,7 @@ import { userProfile, uuid, } from '../testUtils/data'; + import { getExpectedInput } from './testUtils/getExpectedInput'; jest.mock('uuid'); diff --git a/packages/core/__tests__/singleton/Singleton.test.ts b/packages/core/__tests__/singleton/Singleton.test.ts index 0b12a8e9bac..0d0751bfdd9 100644 --- a/packages/core/__tests__/singleton/Singleton.test.ts +++ b/packages/core/__tests__/singleton/Singleton.test.ts @@ -1,10 +1,12 @@ +import { TextDecoder, TextEncoder } from 'util'; + import { Amplify } from '../../src/singleton'; -import { Hub, AMPLIFY_SYMBOL } from '../../src/Hub'; +import { AMPLIFY_SYMBOL, Hub } from '../../src/Hub'; import { AuthClass as Auth } from '../../src/singleton/Auth'; import { decodeJWT } from '../../src/singleton/Auth/utils'; import { CredentialsAndIdentityId } from '../../src/singleton/Auth/types'; -import { TextEncoder, TextDecoder } from 'util'; -import { fetchAuthSession, ResourcesConfig } from '../../src'; +import { ResourcesConfig, fetchAuthSession } from '../../src'; + Object.assign(global, { TextDecoder, TextEncoder }); jest.mock('../../src/Hub', () => ({ @@ -521,6 +523,7 @@ describe('Session tests', () => { const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE3MTAyOTMxMzB9.YzDpgJsrB3z-ZU1XxMcXSQsMbgCzwH_e-_76rnfehh0'; const mockToken = decodeJWT(token); + return { accessToken: mockToken, }; diff --git a/packages/core/__tests__/storage/CookieStorage.test.ts b/packages/core/__tests__/storage/CookieStorage.test.ts index 75ef343691c..d3093ec7e94 100644 --- a/packages/core/__tests__/storage/CookieStorage.test.ts +++ b/packages/core/__tests__/storage/CookieStorage.test.ts @@ -3,7 +3,7 @@ import { CookieStorage } from '../../src/storage/CookieStorage'; const cookieStorageDomain = 'https://testdomain.com'; describe('CookieStorage', () => { - //defining a DOM to attach a cookie to + // defining a DOM to attach a cookie to Object.defineProperty(document, 'cookie', { writable: true }); describe('Constructor methods', () => { diff --git a/packages/core/__tests__/utils.test.ts b/packages/core/__tests__/utils.test.ts index 09be22a39da..1968709f609 100644 --- a/packages/core/__tests__/utils.test.ts +++ b/packages/core/__tests__/utils.test.ts @@ -1,8 +1,8 @@ 'use strict'; import { - jitteredExponentialRetry, NonRetryableError, + jitteredExponentialRetry, urlSafeDecode, urlSafeEncode, } from '../src/utils'; diff --git a/packages/core/__tests__/utils/generateRandomString.test.ts b/packages/core/__tests__/utils/generateRandomString.test.ts index 2717e3a3743..d17cb37c9d7 100644 --- a/packages/core/__tests__/utils/generateRandomString.test.ts +++ b/packages/core/__tests__/utils/generateRandomString.test.ts @@ -17,6 +17,7 @@ describe('generateRandomString()', () => { mathRandomSpy.mockImplementation(() => { const returnValue = counter; counter += 5; + return parseFloat(`0.${returnValue}`); }); diff --git a/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts b/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts index 131199c3e84..fe0b5cea7b4 100644 --- a/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts +++ b/packages/core/__tests__/utils/globalHelpers/globalHelpers.native.test.ts @@ -1,15 +1,16 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -const mockCrypto = { getRandomValues: jest.fn() }; +import { loadBase64, loadGetRandomValues } from '@aws-amplify/react-native'; -import { loadGetRandomValues, loadBase64 } from '@aws-amplify/react-native'; import { getAtob, getBtoa, 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(() => { diff --git a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts index a3eef512e09..8dae69b5342 100644 --- a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts +++ b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { loadAsyncStorage } from '@aws-amplify/react-native'; + import { createQueuedStorage, keyPrefix, From cb03295d15137a4a47bfb9bbd800d643786d91d7 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 11 Mar 2024 14:56:04 -0700 Subject: [PATCH 07/14] 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 fe412087332..6165f8a814d 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 9bc7738947a..41b31cf0815 100644 --- a/packages/core/__tests__/ConsoleLogger.test.ts +++ b/packages/core/__tests__/ConsoleLogger.test.ts @@ -38,16 +38,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, }); From aaf47f949b6f6581ed0aa852b4a16bf88d1d78b4 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Mon, 18 Mar 2024 15:42:06 -0700 Subject: [PATCH 08/14] apply suggestions --- .../__tests__/BackgroundProcessManager.test.ts | 2 +- packages/core/__tests__/ConsoleLogger.test.ts | 15 +++++++++------ .../__tests__/clients/composeApiHandler.test.ts | 8 ++++---- .../queuedStorage/queuedStorage.native.test.ts | 5 ----- 4 files changed, 14 insertions(+), 16 deletions(-) diff --git a/packages/core/__tests__/BackgroundProcessManager.test.ts b/packages/core/__tests__/BackgroundProcessManager.test.ts index 75fa2bbc1e0..9b83e0b01fb 100644 --- a/packages/core/__tests__/BackgroundProcessManager.test.ts +++ b/packages/core/__tests__/BackgroundProcessManager.test.ts @@ -428,7 +428,7 @@ describe('BackgroundProcessManager', () => { const manager = new BackgroundProcessManager(); let count = 0; - const _ = new Observable(observer => { + new Observable(observer => { const interval = setInterval(() => { observer.next({}); }, 10); diff --git a/packages/core/__tests__/ConsoleLogger.test.ts b/packages/core/__tests__/ConsoleLogger.test.ts index 41b31cf0815..0025f29ab71 100644 --- a/packages/core/__tests__/ConsoleLogger.test.ts +++ b/packages/core/__tests__/ConsoleLogger.test.ts @@ -1,15 +1,18 @@ import { ConsoleLogger } from '../src'; -import { LoggingProvider, LogType } from '../src/Logger/types'; +import { LogType, LoggingProvider } from '../src/Logger/types'; type LogEvent = 'verbose' | 'debug' | 'info' | 'warn' | 'error'; describe('ConsoleLogger', () => { + const noop = () => { + // no op + }; beforeAll(() => { - jest.spyOn(console, 'log').mockImplementation(() => {}); - jest.spyOn(console, 'error').mockImplementation(() => {}); - jest.spyOn(console, 'warn').mockImplementation(() => {}); - jest.spyOn(console, 'info').mockImplementation(() => {}); - jest.spyOn(console, 'debug').mockImplementation(() => {}); + jest.spyOn(console, 'log').mockImplementation(noop); + jest.spyOn(console, 'error').mockImplementation(noop); + jest.spyOn(console, 'warn').mockImplementation(noop); + jest.spyOn(console, 'info').mockImplementation(noop); + jest.spyOn(console, 'debug').mockImplementation(noop); }); afterEach(() => { jest.clearAllMocks(); diff --git a/packages/core/__tests__/clients/composeApiHandler.test.ts b/packages/core/__tests__/clients/composeApiHandler.test.ts index eeaec7ec17b..9a31abbdac5 100644 --- a/packages/core/__tests__/clients/composeApiHandler.test.ts +++ b/packages/core/__tests__/clients/composeApiHandler.test.ts @@ -22,8 +22,8 @@ describe(composeServiceApi.name, () => { const mockTransferHandler = jest.fn().mockResolvedValue(defaultResponse); const api = composeServiceApi( mockTransferHandler, - _ => defaultRequest, - async _ => ({ + () => defaultRequest, + async () => ({ Result: 'from API', }), defaultConfig, @@ -47,8 +47,8 @@ describe(composeServiceApi.name, () => { }; const api = composeServiceApi( mockTransferHandler, - __ => defaultRequest, - async __ => ({ + () => defaultRequest, + async () => ({ Result: 'from API', }), defaultConfig, diff --git a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts index 4bae7b803c2..80395206eb0 100644 --- a/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts +++ b/packages/core/__tests__/utils/queuedStorage/queuedStorage.native.test.ts @@ -131,7 +131,6 @@ describe('createQueuedStorage', () => { describe('method add()', () => { let queuedStorage: QueuedStorage; - // let originalDate; let dateNowSpy: jest.SpyInstance; const testInput: ItemToAdd = { content: 'some log content', @@ -139,10 +138,6 @@ describe('createQueuedStorage', () => { }; beforeAll(() => { - // originalDate = Date; - // Date = { - // now: jest.fn(() => 123), - // } as any; dateNowSpy = jest.spyOn(Date, 'now').mockReturnValue(123); queuedStorage = createQueuedStorage(); }); From 9bc046ebb87d2cff327c56869066c0d706ec3441 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 19 Mar 2024 14:44:52 -0700 Subject: [PATCH 09/14] turn off node callback function convention check --- .eslintrc.js | 1 + 1 file changed, 1 insertion(+) diff --git a/.eslintrc.js b/.eslintrc.js index 6165f8a814d..73687a1364c 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -126,6 +126,7 @@ module.exports = { 'no-useless-constructor': 'off', 'no-trailing-spaces': 'error', 'no-return-await': 'error', + 'n/no-callback-literal': 'off', 'object-shorthand': 'error', 'prefer-destructuring': 'off', 'promise/catch-or-return': [ From 0d9a8a035e8493f7c67042b259b979bf9a943498 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 19 Mar 2024 14:45:34 -0700 Subject: [PATCH 10/14] do not mock console functions globaly but noopify them --- jest.setup.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/jest.setup.js b/jest.setup.js index 05fbee97db1..b662755c6ea 100644 --- a/jest.setup.js +++ b/jest.setup.js @@ -1,12 +1,14 @@ // Suppress console messages printing during unit tests. // Comment out log level as necessary (e.g. while debugging tests) +const noop = () => undefined; + global.console = { ...console, - log: jest.fn(), - debug: jest.fn(), - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), + log: noop, + debug: noop, + info: noop, + warn: noop, + error: noop, }; // React Native global From 1e7d3ca102a325261df54d1e0342a9cce64b8491 Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 19 Mar 2024 14:45:41 -0700 Subject: [PATCH 11/14] apply suggestions --- .../__tests__/api/generateServerClient.test.ts | 4 +--- .../__tests__/BackgroundProcessManager.test.ts | 14 ++++---------- packages/core/__tests__/ConsoleLogger.test.ts | 17 ++++++----------- packages/core/__tests__/Hub.test.ts | 16 ++++------------ .../__tests__/Platform/customUserAgent.test.ts | 6 ++++-- packages/core/__tests__/ServiceWorker.test.ts | 4 +--- .../clients/composeTransferHandler.test.ts | 2 +- packages/core/__tests__/clients/fetch.test.ts | 4 ++-- .../core/__tests__/singleton/Singleton.test.ts | 14 ++++---------- .../__tests__/storage/CookieStorage.test.ts | 3 +-- .../__tests__/storage/DefaultStorage.test.ts | 10 ++++------ packages/core/__tests__/utils.test.ts | 4 ---- 12 files changed, 32 insertions(+), 66 deletions(-) diff --git a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts index caed424502a..31e28946721 100644 --- a/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts +++ b/packages/adapter-nextjs/__tests__/api/generateServerClient.test.ts @@ -95,9 +95,7 @@ describe('generateServerClient', () => { })); jest.mock('@aws-amplify/core/internals/adapter-core', () => ({ - getAmplifyServerContext: () => { - // no-op for testing - }, + getAmplifyServerContext: jest.fn(), })); const client = generateServerClientUsingReqRes({ diff --git a/packages/core/__tests__/BackgroundProcessManager.test.ts b/packages/core/__tests__/BackgroundProcessManager.test.ts index 9b83e0b01fb..91280ec0637 100644 --- a/packages/core/__tests__/BackgroundProcessManager.test.ts +++ b/packages/core/__tests__/BackgroundProcessManager.test.ts @@ -512,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(_ => manager.close()); + const closes = [0, 1, 2, 3, 4, 5].map(() => manager.close()); // ensure everything has settled const resolved = await Promise.allSettled(closes); @@ -631,9 +631,7 @@ describe('BackgroundProcessManager', () => { test('cleaners can be named', async () => { const manager = new BackgroundProcessManager(); - manager.addCleaner(async () => { - // no op - }, 'cleaner name'); + manager.addCleaner(() => Promise.resolve(), 'cleaner name'); expect(manager.pending.length).toBe(1); expect(manager.pending[0]).toEqual('cleaner name'); @@ -646,9 +644,7 @@ describe('BackgroundProcessManager', () => { await manager.close(); await expect( - manager.add(async () => { - // no-op - }, 'some job'), + manager.add(() => Promise.resolve(), 'some job'), ).rejects.toThrow('some job'); }); @@ -664,9 +660,7 @@ describe('BackgroundProcessManager', () => { const close = manager.close(); await expect( - manager.add(async () => { - // no-op - }, 'some job'), + manager.add(() => Promise.resolve(), 'some job'), ).rejects.toThrow('blocking job'); unblock?.(); diff --git a/packages/core/__tests__/ConsoleLogger.test.ts b/packages/core/__tests__/ConsoleLogger.test.ts index 0025f29ab71..02bf526b7e1 100644 --- a/packages/core/__tests__/ConsoleLogger.test.ts +++ b/packages/core/__tests__/ConsoleLogger.test.ts @@ -4,15 +4,12 @@ import { LogType, LoggingProvider } from '../src/Logger/types'; type LogEvent = 'verbose' | 'debug' | 'info' | 'warn' | 'error'; describe('ConsoleLogger', () => { - const noop = () => { - // no op - }; beforeAll(() => { - jest.spyOn(console, 'log').mockImplementation(noop); - jest.spyOn(console, 'error').mockImplementation(noop); - jest.spyOn(console, 'warn').mockImplementation(noop); - jest.spyOn(console, 'info').mockImplementation(noop); - jest.spyOn(console, 'debug').mockImplementation(noop); + jest.spyOn(console, 'log'); + jest.spyOn(console, 'error'); + jest.spyOn(console, 'warn'); + jest.spyOn(console, 'info'); + jest.spyOn(console, 'debug'); }); afterEach(() => { jest.clearAllMocks(); @@ -50,9 +47,7 @@ describe('ConsoleLogger', () => { configure: () => { return {}; }, - pushLogs: () => { - // no-op - }, + pushLogs: jest.fn(), } as LoggingProvider; const logger = new ConsoleLogger('name'); diff --git a/packages/core/__tests__/Hub.test.ts b/packages/core/__tests__/Hub.test.ts index b1250fe8c86..e7cd42a8f4f 100644 --- a/packages/core/__tests__/Hub.test.ts +++ b/packages/core/__tests__/Hub.test.ts @@ -9,9 +9,7 @@ describe('Hub', () => { }); test('happy case', () => { - const listener = jest.fn(() => { - // no-op - }); + const listener = jest.fn(); Hub.listen('auth', listener); @@ -30,9 +28,7 @@ describe('Hub', () => { }); test('Protected channel', () => { - const listener = jest.fn(() => { - // no-op - }); + const listener = jest.fn(); Hub.listen('auth', listener); @@ -54,9 +50,7 @@ describe('Hub', () => { }); test('Protected channel - ui', () => { - const listener = jest.fn(() => { - // no-op - }); + const listener = jest.fn(); Hub.listen('ui', listener); @@ -73,9 +67,7 @@ describe('Hub', () => { ); }); test('Remove listener', () => { - const listener = jest.fn(() => { - // no-op - }); + const listener = jest.fn(); const unsubscribe = Hub.listen('auth', listener); diff --git a/packages/core/__tests__/Platform/customUserAgent.test.ts b/packages/core/__tests__/Platform/customUserAgent.test.ts index b891d2da041..dfe8e1f2098 100644 --- a/packages/core/__tests__/Platform/customUserAgent.test.ts +++ b/packages/core/__tests__/Platform/customUserAgent.test.ts @@ -27,8 +27,10 @@ describe('Custom user agent utilities', () => { beforeEach(() => { jest.resetModules(); - ({ getCustomUserAgent } = require('../../src/Platform/customUserAgent')); - ({ setCustomUserAgent } = require('../../src/Platform/customUserAgent')); + ({ + getCustomUserAgent, + setCustomUserAgent, + } = require('../../src/Platform/customUserAgent')); }); it('sets custom user agent state for multiple categories and APIs', () => { diff --git a/packages/core/__tests__/ServiceWorker.test.ts b/packages/core/__tests__/ServiceWorker.test.ts index cdb04616d81..6f2c6232aeb 100644 --- a/packages/core/__tests__/ServiceWorker.test.ts +++ b/packages/core/__tests__/ServiceWorker.test.ts @@ -40,9 +40,7 @@ describe('ServiceWorker test', () => { test(`can register (${status})`, () => { const bla = { [status]: { - addEventListener: () => { - // no-op - }, + addEventListener: jest.fn(), }, }; (global as any).navigator.serviceWorker = { diff --git a/packages/core/__tests__/clients/composeTransferHandler.test.ts b/packages/core/__tests__/clients/composeTransferHandler.test.ts index 617beb19b00..4f4fea727f9 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, _) => async request => { + (options: OptionsType) => next => async request => { request.body += 'A'; options.mockFnInOptions('A'); const resp = await next(request); diff --git a/packages/core/__tests__/clients/fetch.test.ts b/packages/core/__tests__/clients/fetch.test.ts index 694e351c7a7..0c271aae1d3 100644 --- a/packages/core/__tests__/clients/fetch.test.ts +++ b/packages/core/__tests__/clients/fetch.test.ts @@ -68,8 +68,8 @@ describe(fetchTransferHandler.name, () => { }); it('should support headers', async () => { - mockFetchResponse.headers.forEach.mockImplementation((funcParam: any) => { - funcParam('foo', 'bar'); + mockFetchResponse.headers.forEach.mockImplementation((callback: any) => { + callback('foo', 'bar'); }); const { headers } = await fetchTransferHandler(mockRequest, {}); expect(headers).toEqual({ bar: 'foo' }); diff --git a/packages/core/__tests__/singleton/Singleton.test.ts b/packages/core/__tests__/singleton/Singleton.test.ts index 9726aa0fb87..03c0185359d 100644 --- a/packages/core/__tests__/singleton/Singleton.test.ts +++ b/packages/core/__tests__/singleton/Singleton.test.ts @@ -297,9 +297,7 @@ describe('Session tests', () => { credentials: mockCredentials, }; }, - clearCredentialsAndIdentityId: () => { - // no-op - }, + clearCredentialsAndIdentityId: jest.fn(), }, }, }, @@ -365,7 +363,7 @@ describe('Session tests', () => { }; const credentialsSpy = jest.fn( - async (_): Promise => { + async (): Promise => { return { credentials: { accessKeyId: 'accessKeyIdValue', @@ -391,9 +389,7 @@ describe('Session tests', () => { Auth: { credentialsProvider: { getCredentialsAndIdentityId: credentialsSpy, - clearCredentialsAndIdentityId: () => { - // no-op - }, + clearCredentialsAndIdentityId: jest.fn(), }, tokenProvider: { getTokens: spyTokenProvider, @@ -479,9 +475,7 @@ describe('Session tests', () => { Auth: { credentialsProvider: { getCredentialsAndIdentityId: credentialsSpy, - clearCredentialsAndIdentityId: () => { - // no-op - }, + clearCredentialsAndIdentityId: jest.fn(), }, tokenProvider: { getTokens: spyTokenProvider, diff --git a/packages/core/__tests__/storage/CookieStorage.test.ts b/packages/core/__tests__/storage/CookieStorage.test.ts index 04422d40138..89538d66034 100644 --- a/packages/core/__tests__/storage/CookieStorage.test.ts +++ b/packages/core/__tests__/storage/CookieStorage.test.ts @@ -17,8 +17,7 @@ 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 }); + const _ = new CookieStorage({ sameSite: undefined }); }).toThrow(expectedError); expect(() => { // eslint-disable-next-line no-new diff --git a/packages/core/__tests__/storage/DefaultStorage.test.ts b/packages/core/__tests__/storage/DefaultStorage.test.ts index 8071acb785a..47214d899d7 100644 --- a/packages/core/__tests__/storage/DefaultStorage.test.ts +++ b/packages/core/__tests__/storage/DefaultStorage.test.ts @@ -25,16 +25,14 @@ describe('DefaultStorage', () => { expect(await defaultStorage.getItem(key)).toEqual(secondValue); }); - it('should not throw if trying to delete a non existing key', async () => { + it('should not throw if trying to delete a non existing key', () => { const badKey = 'nonExistingKey'; - // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression - await expect(() => { - defaultStorage.removeItem(badKey); - }).not.toThrow(); + + expect(defaultStorage.removeItem(badKey)).resolves.toBeUndefined(); }); it('should clear out storage', async () => { await defaultStorage.clear(); - expect(await defaultStorage.getItem(key)).toBeNull(); + expect(defaultStorage.getItem(key)).resolves.toBeNull(); }); }); diff --git a/packages/core/__tests__/utils.test.ts b/packages/core/__tests__/utils.test.ts index f81b689842c..71444c4f8cf 100644 --- a/packages/core/__tests__/utils.test.ts +++ b/packages/core/__tests__/utils.test.ts @@ -14,10 +14,6 @@ import { DateUtils } from '../src/Signer/DateUtils'; ConsoleLogger.LOG_LEVEL = 'DEBUG'; describe('Util', () => { - beforeEach(() => { - // no-op - }); - describe('DateUtils', () => { test('isClockSkewError', () => { expect( From 7b41395d6b0b4071fde74a58bf78aa177315e69e Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Wed, 20 Mar 2024 11:46:21 -0700 Subject: [PATCH 12/14] Revert "do not mock console functions globaly but noopify them" This reverts commit 913b11e2959e20014b093910f8661da1dc7a2b2e. --- jest.setup.js | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/jest.setup.js b/jest.setup.js index b662755c6ea..05fbee97db1 100644 --- a/jest.setup.js +++ b/jest.setup.js @@ -1,14 +1,12 @@ // Suppress console messages printing during unit tests. // Comment out log level as necessary (e.g. while debugging tests) -const noop = () => undefined; - global.console = { ...console, - log: noop, - debug: noop, - info: noop, - warn: noop, - error: noop, + log: jest.fn(), + debug: jest.fn(), + info: jest.fn(), + warn: jest.fn(), + error: jest.fn(), }; // React Native global From cf8bc046b96d8e88e6f32b088723443dddc5398f Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Thu, 21 Mar 2024 09:25:29 -0700 Subject: [PATCH 13/14] refactor a no-op function --- packages/core/__tests__/BackgroundProcessManager.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/core/__tests__/BackgroundProcessManager.test.ts b/packages/core/__tests__/BackgroundProcessManager.test.ts index 91280ec0637..b2e5f95ea08 100644 --- a/packages/core/__tests__/BackgroundProcessManager.test.ts +++ b/packages/core/__tests__/BackgroundProcessManager.test.ts @@ -176,9 +176,7 @@ describe('BackgroundProcessManager', () => { expect(manager.isClosing).toBe(false); expect(manager.isClosed).toBe(false); - let unblock: () => void = () => { - // no op - }; + let unblock: () => void = () => undefined; manager.add( async () => new Promise(resolve => { From 1a830db9ef2946a1804d932aa818e3283fcde82a Mon Sep 17 00:00:00 2001 From: Hui Zhao Date: Tue, 26 Mar 2024 16:36:52 -0700 Subject: [PATCH 14/14] remove // eslint-disable-next-line no-new --- packages/core/__tests__/storage/CookieStorage.test.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/core/__tests__/storage/CookieStorage.test.ts b/packages/core/__tests__/storage/CookieStorage.test.ts index 89538d66034..c16e57920bf 100644 --- a/packages/core/__tests__/storage/CookieStorage.test.ts +++ b/packages/core/__tests__/storage/CookieStorage.test.ts @@ -20,15 +20,13 @@ describe('CookieStorage', () => { const _ = new CookieStorage({ sameSite: undefined }); }).toThrow(expectedError); expect(() => { - // eslint-disable-next-line no-new - new CookieStorage({ sameSite: 'foo' as any }); + const _ = 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({ + const _ = new CookieStorage({ domain: cookieStorageDomain, secure: false, sameSite: 'none',