diff --git a/packages/analytics/__tests__/providers/kinesis-firehose/utils/resolveConfig.test.ts b/packages/analytics/__tests__/providers/kinesis-firehose/utils/resolveConfig.test.ts index e93dec1b876..74729e886d3 100644 --- a/packages/analytics/__tests__/providers/kinesis-firehose/utils/resolveConfig.test.ts +++ b/packages/analytics/__tests__/providers/kinesis-firehose/utils/resolveConfig.test.ts @@ -16,12 +16,27 @@ describe('Analytics KinesisFirehose Provider Util: resolveConfig', () => { }; const getConfigSpy = jest.spyOn(Amplify, 'getConfig'); + const assertConfiguredSpy = jest.spyOn(Amplify, 'assertConfigured'); beforeEach(() => { getConfigSpy.mockReset(); + assertConfiguredSpy.mockReset(); + }); + + it('throws if Amplify is not configured', () => { + assertConfiguredSpy.mockImplementation(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + expect(resolveConfig).toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); }); it('returns required config', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); getConfigSpy.mockReturnValue({ Analytics: { KinesisFirehose: providedConfig }, }); @@ -30,6 +45,7 @@ describe('Analytics KinesisFirehose Provider Util: resolveConfig', () => { }); it('use default config for optional fields', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); const requiredFields = { region: 'us-east-1', bufferSize: undefined, diff --git a/packages/analytics/__tests__/providers/kinesis/utils/resolveConfig.test.ts b/packages/analytics/__tests__/providers/kinesis/utils/resolveConfig.test.ts index ad4d079a910..4eddeb524ef 100644 --- a/packages/analytics/__tests__/providers/kinesis/utils/resolveConfig.test.ts +++ b/packages/analytics/__tests__/providers/kinesis/utils/resolveConfig.test.ts @@ -16,12 +16,27 @@ describe('Analytics Kinesis Provider Util: resolveConfig', () => { }; const getConfigSpy = jest.spyOn(Amplify, 'getConfig'); + const assertConfiguredSpy = jest.spyOn(Amplify, 'assertConfigured'); beforeEach(() => { getConfigSpy.mockReset(); + assertConfiguredSpy.mockReset(); + }); + + it('throws if Amplify is not configured', () => { + assertConfiguredSpy.mockImplementation(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + expect(resolveConfig).toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); }); it('returns required config', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); getConfigSpy.mockReturnValue({ Analytics: { Kinesis: kinesisConfig }, }); @@ -30,6 +45,7 @@ describe('Analytics Kinesis Provider Util: resolveConfig', () => { }); it('use default config for optional fields', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); const requiredFields = { region: 'us-east-1', bufferSize: undefined, diff --git a/packages/analytics/__tests__/providers/personalize/utils/resolveConfig.test.ts b/packages/analytics/__tests__/providers/personalize/utils/resolveConfig.test.ts index 3f39f1db69f..ba0e848934e 100644 --- a/packages/analytics/__tests__/providers/personalize/utils/resolveConfig.test.ts +++ b/packages/analytics/__tests__/providers/personalize/utils/resolveConfig.test.ts @@ -18,12 +18,27 @@ describe('Analytics Personalize Provider Util: resolveConfig', () => { }; const getConfigSpy = jest.spyOn(Amplify, 'getConfig'); + const assertConfiguredSpy = jest.spyOn(Amplify, 'assertConfigured'); beforeEach(() => { getConfigSpy.mockReset(); + assertConfiguredSpy.mockReset(); + }); + + it('throws if Amplify is not configured', () => { + assertConfiguredSpy.mockImplementation(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + expect(resolveConfig).toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); }); it('returns required config', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); getConfigSpy.mockReturnValue({ Analytics: { Personalize: providedConfig }, }); @@ -35,6 +50,7 @@ describe('Analytics Personalize Provider Util: resolveConfig', () => { }); it('use default config for optional fields', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); const requiredFields = { region: 'us-east-1', trackingId: 'trackingId1', diff --git a/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts b/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts index 562d3d2f29a..3704e07329b 100644 --- a/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts +++ b/packages/analytics/__tests__/providers/pinpoint/utils/resolveConfig.test.ts @@ -16,12 +16,27 @@ describe('Analytics Pinpoint Provider Util: resolveConfig', () => { }; // create spies const getConfigSpy = jest.spyOn(Amplify, 'getConfig'); + const assertConfiguredSpy = jest.spyOn(Amplify, 'assertConfigured'); beforeEach(() => { getConfigSpy.mockReset(); + assertConfiguredSpy.mockReset(); + }); + + it('throws if Amplify is not configured', () => { + assertConfiguredSpy.mockImplementation(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + expect(resolveConfig).toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); }); it('returns required config', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); getConfigSpy.mockReturnValue({ Analytics: { Pinpoint: pinpointConfig }, }); diff --git a/packages/analytics/src/providers/kinesis-firehose/utils/resolveConfig.ts b/packages/analytics/src/providers/kinesis-firehose/utils/resolveConfig.ts index 4de7639c4b6..a5f7f350c9f 100644 --- a/packages/analytics/src/providers/kinesis-firehose/utils/resolveConfig.ts +++ b/packages/analytics/src/providers/kinesis-firehose/utils/resolveConfig.ts @@ -11,6 +11,7 @@ import { import { DEFAULT_KINESIS_FIREHOSE_CONFIG } from './constants'; export const resolveConfig = () => { + Amplify.assertConfigured(); const config = Amplify.getConfig().Analytics?.KinesisFirehose; const { region, diff --git a/packages/analytics/src/providers/kinesis/utils/resolveConfig.ts b/packages/analytics/src/providers/kinesis/utils/resolveConfig.ts index c4407c2cf48..35b07768993 100644 --- a/packages/analytics/src/providers/kinesis/utils/resolveConfig.ts +++ b/packages/analytics/src/providers/kinesis/utils/resolveConfig.ts @@ -11,6 +11,7 @@ import { import { DEFAULT_KINESIS_CONFIG } from './constants'; export const resolveConfig = () => { + Amplify.assertConfigured(); const config = Amplify.getConfig().Analytics?.Kinesis; const { region, diff --git a/packages/analytics/src/providers/personalize/utils/resolveConfig.ts b/packages/analytics/src/providers/personalize/utils/resolveConfig.ts index fac8556b6ca..edee7345be4 100644 --- a/packages/analytics/src/providers/personalize/utils/resolveConfig.ts +++ b/packages/analytics/src/providers/personalize/utils/resolveConfig.ts @@ -14,6 +14,7 @@ import { } from './constants'; export const resolveConfig = () => { + Amplify.assertConfigured(); const config = Amplify.getConfig().Analytics?.Personalize; const { region, diff --git a/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts b/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts index f60b7a2fd53..5cd8b7caec9 100644 --- a/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts +++ b/packages/analytics/src/providers/pinpoint/utils/resolveConfig.ts @@ -12,6 +12,7 @@ import { * @internal */ export const resolveConfig = () => { + Amplify.assertConfigured(); const { appId, region, bufferSize, flushSize, flushInterval, resendLimit } = Amplify.getConfig().Analytics?.Pinpoint ?? {}; assertValidationError(!!appId, AnalyticsValidationErrorCode.NoAppId); diff --git a/packages/api-rest/__tests__/apis/common/internalPost.test.ts b/packages/api-rest/__tests__/apis/common/internalPost.test.ts index f4887e9d2ad..b3f110238de 100644 --- a/packages/api-rest/__tests__/apis/common/internalPost.test.ts +++ b/packages/api-rest/__tests__/apis/common/internalPost.test.ts @@ -22,10 +22,13 @@ const mockAuthenticatedHandler = authenticatedHandler as jest.Mock; const mockUnauthenticatedHandler = unauthenticatedHandler as jest.Mock; const mockParseJsonError = parseJsonError as jest.Mock; const mockFetchAuthSession = jest.fn(); +const mockAssertConfigured = jest.fn(); const mockAmplifyInstance = { Auth: { fetchAuthSession: mockFetchAuthSession, }, + isConfigured: true, + assertConfigured: mockAssertConfigured, } as any as AmplifyClassV6; const successResponse = { @@ -52,6 +55,7 @@ describe('internal post', () => { mockFetchAuthSession.mockResolvedValue({ credentials }); mockAuthenticatedHandler.mockResolvedValue(successResponse); mockUnauthenticatedHandler.mockResolvedValue(successResponse); + mockAssertConfigured.mockReturnValue(true); }); it('should call authenticatedHandler with specified region from signingServiceInfo', async () => { diff --git a/packages/api-rest/__tests__/apis/common/publicApis.test.ts b/packages/api-rest/__tests__/apis/common/publicApis.test.ts index 6a0a4857581..49ea580cae0 100644 --- a/packages/api-rest/__tests__/apis/common/publicApis.test.ts +++ b/packages/api-rest/__tests__/apis/common/publicApis.test.ts @@ -46,11 +46,13 @@ const mockConfig = { const mockParseJsonError = parseJsonError as jest.Mock; const mockRestHeaders = jest.fn(); const mockGetConfig = jest.fn(); +const mockAssertConfigured = jest.fn(); const mockAmplifyInstance = { Auth: { fetchAuthSession: mockFetchAuthSession, }, getConfig: mockGetConfig, + assertConfigured: mockAssertConfigured, libraryOptions: { API: { REST: { @@ -86,6 +88,7 @@ describe('public APIs', () => { mockAuthenticatedHandler.mockResolvedValue(mockSuccessResponse); mockUnauthenticatedHandler.mockResolvedValue(mockSuccessResponse); mockGetConfig.mockReturnValue(mockConfig); + mockAssertConfigured.mockReturnValue(true); }); const APIs = [ { name: 'get', fn: get, method: 'GET' }, diff --git a/packages/api-rest/src/apis/common/handler.ts b/packages/api-rest/src/apis/common/handler.ts index d17a8c72b6a..bde95b77d41 100644 --- a/packages/api-rest/src/apis/common/handler.ts +++ b/packages/api-rest/src/apis/common/handler.ts @@ -48,6 +48,7 @@ export const transferHandler = async ( ) => boolean, signingServiceInfo?: SigningServiceInfo, ): Promise => { + amplify.assertConfigured(); const { url, method, headers, body, withCredentials, abortSignal } = options; const resolvedBody = body ? body instanceof FormData @@ -101,6 +102,7 @@ export const transferHandler = async ( const resolveCredentials = async ( amplify: AmplifyClassV6, ): Promise => { + amplify.assertConfigured(); try { const { credentials } = await amplify.Auth.fetchAuthSession(); if (credentials) { diff --git a/packages/api-rest/src/apis/common/internalPost.ts b/packages/api-rest/src/apis/common/internalPost.ts index 6dabea22072..2981f42b7f4 100644 --- a/packages/api-rest/src/apis/common/internalPost.ts +++ b/packages/api-rest/src/apis/common/internalPost.ts @@ -57,6 +57,7 @@ export const post = ( amplify: AmplifyClassV6, { url, options, abortController }: InternalPostInput, ): Promise => { + amplify.assertConfigured(); const controller = abortController ?? new AbortController(); const responsePromise = createCancellableOperation(async () => { const response = transferHandler( diff --git a/packages/api-rest/src/apis/common/publicApis.ts b/packages/api-rest/src/apis/common/publicApis.ts index 8c7a58cb6fc..de7f0d22d03 100644 --- a/packages/api-rest/src/apis/common/publicApis.ts +++ b/packages/api-rest/src/apis/common/publicApis.ts @@ -35,6 +35,7 @@ const publicHandler = ( method: string, ) => createCancellableOperation(async abortSignal => { + amplify.assertConfigured(); const { apiName, options: apiOptions = {}, path: apiPath } = options; const url = resolveApiUrl( amplify, diff --git a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts index d07979c5d9c..b9da4f9b240 100644 --- a/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmResetPassword.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts index ce786ece3cb..554dbe5daa3 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignInErrorCases.test.ts @@ -14,7 +14,7 @@ import { authAPITestParams } from './testUtils/authApiTestParams'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('../../../src/client/utils/store'); jest.mock( diff --git a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts index 3523f9495aa..e305be006e5 100644 --- a/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmSignUp.test.ts @@ -22,7 +22,7 @@ jest.mock('../../../src/providers/cognito/factories'); jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts index 56608241897..cae67a141ab 100644 --- a/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts +++ b/packages/auth/__tests__/providers/cognito/confirmUserAttribute.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts index b56e9736e12..d22ab182bb8 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUser.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUser.test.ts @@ -17,7 +17,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts index c791b224fdb..88384af9e81 100644 --- a/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/deleteUserAttributes.test.ts @@ -15,7 +15,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts index 08394a09aa9..cae0669d28d 100644 --- a/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchDevices.test.ts @@ -15,7 +15,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts index 18dba7d80f0..cfbd31f0ee7 100644 --- a/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchMFAPreference.test.ts @@ -15,7 +15,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock( '../../../src/foundation/factories/serviceClients/cognitoIdentityProvider', diff --git a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts index 87cf79e715d..4ce5eb8e163 100644 --- a/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/fetchUserAttributes.test.ts @@ -15,7 +15,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), @@ -34,6 +34,7 @@ describe('fetchUserAttributes', () => { const mockCreateCognitoUserPoolEndpointResolver = jest.mocked( createCognitoUserPoolEndpointResolver, ); + const mockAssertConfigured = Amplify.assertConfigured as jest.Mock; beforeAll(() => { setUpGetConfig(Amplify); @@ -43,6 +44,7 @@ describe('fetchUserAttributes', () => { }); beforeEach(() => { + mockAssertConfigured.mockReturnValue(undefined); mockGetUser.mockResolvedValue({ UserAttributes: [ { Name: 'email', Value: 'XXXXXXXXXXXXX' }, @@ -60,6 +62,7 @@ describe('fetchUserAttributes', () => { mockGetUser.mockReset(); mockFetchAuthSession.mockClear(); mockCreateGetUserClient.mockClear(); + mockAssertConfigured.mockReset(); }); it('should return the current user attributes into a map format', async () => { diff --git a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts index cc0a2d37407..32b2f5345fd 100644 --- a/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/forgetDevice.test.ts @@ -17,7 +17,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts b/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts index 1860c2dccd2..611c9a01607 100644 --- a/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts +++ b/packages/auth/__tests__/providers/cognito/getCurrentUser.test.ts @@ -13,7 +13,11 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { Auth: { getTokens: jest.fn() }, getConfig: jest.fn(() => ({})) }, + Amplify: { + Auth: { getTokens: jest.fn() }, + getConfig: jest.fn(() => ({})), + assertConfigured: jest.fn(), + }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), @@ -25,12 +29,14 @@ describe('getCurrentUser', () => { const mockedUsername = 'XXXXXXXXXXXXXX'; // assert mocks const mockGetTokensFunction = Amplify.Auth.getTokens as jest.Mock; + const mockAssertConfigured = Amplify.assertConfigured as jest.Mock; beforeAll(() => { setUpGetConfig(Amplify); }); beforeEach(() => { + mockAssertConfigured.mockReturnValue(undefined); mockGetTokensFunction.mockResolvedValue({ accessToken: decodeJWT(mockAccessToken), idToken: { @@ -48,6 +54,7 @@ describe('getCurrentUser', () => { afterEach(() => { mockGetTokensFunction.mockReset(); + mockAssertConfigured.mockReset(); }); it('should get current user', async () => { @@ -71,4 +78,16 @@ describe('getCurrentUser', () => { expect(error.name).toBe(USER_UNAUTHENTICATED_EXCEPTION); } }); + + it('throws if Amplify is not configured', async () => { + mockAssertConfigured.mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + expect(getCurrentUser()).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); }); diff --git a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts index 0521e928654..86ae52e3be3 100644 --- a/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts +++ b/packages/auth/__tests__/providers/cognito/rememberDevice.test.ts @@ -17,7 +17,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts index d351a950484..2edb0f081a7 100644 --- a/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/resendSignUpCode.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts index 41deeeb170a..45538c8687c 100644 --- a/packages/auth/__tests__/providers/cognito/resetPassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/resetPassword.test.ts @@ -15,7 +15,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts index 31376edf642..1a515b48cb6 100644 --- a/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts +++ b/packages/auth/__tests__/providers/cognito/sendUserAttributeVerificationCode.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts index 1a7d0cfbc4b..fa88b36d58a 100644 --- a/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts +++ b/packages/auth/__tests__/providers/cognito/setUpTOTP.test.ts @@ -15,7 +15,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts index 94b4029418b..aea10819d94 100644 --- a/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInErrorCases.test.ts @@ -17,7 +17,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), @@ -35,6 +35,7 @@ describe('signIn API error path cases:', () => { const mockInitiateAuth = jest.fn(); const mockedGetCurrentUser = getCurrentUser as jest.Mock; + const mockAssertConfigured = Amplify.assertConfigured as jest.Mock; beforeAll(() => { setUpGetConfig(Amplify); @@ -131,4 +132,24 @@ describe('signIn API error path cases:', () => { }), ); }); + + it('throws if Amplify is not configured', async () => { + mockAssertConfigured.mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + const signInResultPromise = signIn({ + username: authAPITestParams.user1.username, + password: authAPITestParams.user1.password, + options: { + authFlowType: 'USER_PASSWORD_AUTH', + }, + }); + + expect(signInResultPromise).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); }); diff --git a/packages/auth/__tests__/providers/cognito/signInResumable.test.ts b/packages/auth/__tests__/providers/cognito/signInResumable.test.ts index 7bc3a8d324a..b7cd6f398bc 100644 --- a/packages/auth/__tests__/providers/cognito/signInResumable.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInResumable.test.ts @@ -27,6 +27,7 @@ jest.mock('@aws-amplify/core', () => ({ Amplify: { getConfig: jest.fn(() => ({})), ADD_OAUTH_LISTENER: jest.fn(() => ({})), + assertConfigured: jest.fn(), }, syncSessionStorage: { setItem: jest.fn((key, value) => { diff --git a/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts b/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts index 0714c091278..215841d96aa 100644 --- a/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts +++ b/packages/auth/__tests__/providers/cognito/signInWithRedirect.test.ts @@ -41,6 +41,7 @@ jest.mock('@aws-amplify/core', () => { Amplify: { getConfig: jest.fn(() => mockAuthConfigWithOAuth), [ACTUAL_ADD_OAUTH_LISTENER]: jest.fn(), + assertConfigured: jest.fn(), }, ConsoleLogger: jest.fn().mockImplementation(() => { return { warn: jest.fn() }; diff --git a/packages/auth/__tests__/providers/cognito/signUp.test.ts b/packages/auth/__tests__/providers/cognito/signUp.test.ts index 3b3f9bab4c5..8c0e98cdb1a 100644 --- a/packages/auth/__tests__/providers/cognito/signUp.test.ts +++ b/packages/auth/__tests__/providers/cognito/signUp.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts index 0d597b5ec9b..bf4a9e2d40f 100644 --- a/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateMFAPreference.test.ts @@ -22,7 +22,7 @@ type MfaPreferenceValue = MFAPreference | undefined; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts index 72dfe80119e..94b391035c9 100644 --- a/packages/auth/__tests__/providers/cognito/updatePassword.test.ts +++ b/packages/auth/__tests__/providers/cognito/updatePassword.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts b/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts index 4fa6ac086d7..4d34d62beb9 100644 --- a/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateUserAttribute.test.ts @@ -12,7 +12,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts index bfa9643b76d..59187f86e67 100644 --- a/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts +++ b/packages/auth/__tests__/providers/cognito/updateUserAttributes.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts index 0f7c5bcb109..e779b6fc92d 100644 --- a/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts +++ b/packages/auth/__tests__/providers/cognito/verifyTOTPSetup.test.ts @@ -16,7 +16,7 @@ import { setUpGetConfig } from './testUtils/setUpGetConfig'; jest.mock('@aws-amplify/core', () => ({ ...(jest.createMockFromModule('@aws-amplify/core') as object), - Amplify: { getConfig: jest.fn(() => ({})) }, + Amplify: { getConfig: jest.fn(() => ({})), assertConfigured: jest.fn() }, })); jest.mock('@aws-amplify/core/internals/utils', () => ({ ...jest.requireActual('@aws-amplify/core/internals/utils'), diff --git a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts index 5c4edc100cf..26194beb761 100644 --- a/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/confirmResetPassword.ts @@ -29,6 +29,7 @@ import { getRegionFromUserPoolId } from '../../../foundation/parsers'; export async function confirmResetPassword( input: ConfirmResetPasswordInput, ): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts index 48c904d5897..53831cb7110 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignIn.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignIn.ts @@ -52,6 +52,7 @@ import { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata'; export async function confirmSignIn( input: ConfirmSignInInput, ): Promise { + Amplify.assertConfigured(); const { challengeResponse, options } = input; const { username, challengeName, signInSession, signInDetails } = signInStore.getState(); diff --git a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts index c9633531908..20d7ac32ed6 100644 --- a/packages/auth/src/providers/cognito/apis/confirmSignUp.ts +++ b/packages/auth/src/providers/cognito/apis/confirmSignUp.ts @@ -36,6 +36,7 @@ import { resetAutoSignIn } from './autoSignIn'; export async function confirmSignUp( input: ConfirmSignUpInput, ): Promise { + Amplify.assertConfigured(); const { username, confirmationCode, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; diff --git a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts index 8c0c4dba1ad..3cf1b8571ee 100644 --- a/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts +++ b/packages/auth/src/providers/cognito/apis/confirmUserAttribute.ts @@ -29,6 +29,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export async function confirmUserAttribute( input: ConfirmUserAttributeInput, ): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/deleteUser.ts b/packages/auth/src/providers/cognito/apis/deleteUser.ts index 53c0c18c6dd..76a388f733a 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUser.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUser.ts @@ -24,6 +24,7 @@ import { signOut } from './signOut'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function deleteUser(): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts index b958dfacc1f..922a92d3dd2 100644 --- a/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/deleteUserAttributes.ts @@ -25,6 +25,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export async function deleteUserAttributes( input: DeleteUserAttributesInput, ): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userAttributeKeys } = input; diff --git a/packages/auth/src/providers/cognito/apis/fetchDevices.ts b/packages/auth/src/providers/cognito/apis/fetchDevices.ts index 5fda1b8fefc..c1059239bbf 100644 --- a/packages/auth/src/providers/cognito/apis/fetchDevices.ts +++ b/packages/auth/src/providers/cognito/apis/fetchDevices.ts @@ -29,6 +29,7 @@ const MAX_DEVICES = 60; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function fetchDevices(): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts index e6da216ba81..16a3e14d1ca 100644 --- a/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/fetchMFAPreference.ts @@ -25,6 +25,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function fetchMFAPreference(): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts b/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts index 0a3673fd6e4..4b46c71ab93 100644 --- a/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/fetchUserAttributes.ts @@ -15,5 +15,7 @@ import { fetchUserAttributes as fetchUserAttributesInternal } from './internal/f * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export const fetchUserAttributes = (): Promise => { + Amplify.assertConfigured(); + return fetchUserAttributesInternal(Amplify); }; diff --git a/packages/auth/src/providers/cognito/apis/forgetDevice.ts b/packages/auth/src/providers/cognito/apis/forgetDevice.ts index b1ca574e1e4..678339de874 100644 --- a/packages/auth/src/providers/cognito/apis/forgetDevice.ts +++ b/packages/auth/src/providers/cognito/apis/forgetDevice.ts @@ -25,6 +25,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function forgetDevice(input?: ForgetDeviceInput): Promise { + Amplify.assertConfigured(); const { device: { id: externalDeviceKey } = { id: undefined } } = input ?? {}; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); diff --git a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts index 2c35937b8ba..5cd53c7102f 100644 --- a/packages/auth/src/providers/cognito/apis/getCurrentUser.ts +++ b/packages/auth/src/providers/cognito/apis/getCurrentUser.ts @@ -17,5 +17,7 @@ import { getCurrentUser as getCurrentUserInternal } from './internal/getCurrentU * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export const getCurrentUser = async (): Promise => { + Amplify.assertConfigured(); + return getCurrentUserInternal(Amplify); }; diff --git a/packages/auth/src/providers/cognito/apis/rememberDevice.ts b/packages/auth/src/providers/cognito/apis/rememberDevice.ts index eb24022096e..edb0ead2f11 100644 --- a/packages/auth/src/providers/cognito/apis/rememberDevice.ts +++ b/packages/auth/src/providers/cognito/apis/rememberDevice.ts @@ -23,6 +23,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function rememberDevice(): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts index cdda7b980eb..daa0a3b184b 100644 --- a/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts +++ b/packages/auth/src/providers/cognito/apis/resendSignUpCode.ts @@ -31,6 +31,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export async function resendSignUpCode( input: ResendSignUpCodeInput, ): Promise { + Amplify.assertConfigured(); const { username } = input; assertValidationError( !!username, diff --git a/packages/auth/src/providers/cognito/apis/resetPassword.ts b/packages/auth/src/providers/cognito/apis/resetPassword.ts index cd6d37a39ca..e359f94847e 100644 --- a/packages/auth/src/providers/cognito/apis/resetPassword.ts +++ b/packages/auth/src/providers/cognito/apis/resetPassword.ts @@ -33,6 +33,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export async function resetPassword( input: ResetPasswordInput, ): Promise { + Amplify.assertConfigured(); const { username } = input; assertValidationError( !!username, diff --git a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts index 4b04b2a85d1..a6c0e28ed52 100644 --- a/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts +++ b/packages/auth/src/providers/cognito/apis/sendUserAttributeVerificationCode.ts @@ -31,6 +31,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export const sendUserAttributeVerificationCode = async ( input: SendUserAttributeVerificationCodeInput, ): Promise => { + Amplify.assertConfigured(); const { userAttributeKey, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; const clientMetadata = options?.clientMetadata; diff --git a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts index 43dac4c787b..5add901a599 100644 --- a/packages/auth/src/providers/cognito/apis/setUpTOTP.ts +++ b/packages/auth/src/providers/cognito/apis/setUpTOTP.ts @@ -29,6 +29,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. **/ export async function setUpTOTP(): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts index a1260538d17..a39d6bd542a 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomAuth.ts @@ -46,6 +46,7 @@ import { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata'; export async function signInWithCustomAuth( input: SignInWithCustomAuthInput, ): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { username, password, options } = input; diff --git a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts index 3827699f476..72d443f59c7 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithCustomSRPAuth.ts @@ -49,6 +49,7 @@ import { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata'; export async function signInWithCustomSRPAuth( input: SignInWithCustomSRPAuthInput, ): Promise { + Amplify.assertConfigured(); const { username, password, options } = input; const signInDetails: CognitoAuthSignInDetails = { loginId: username, diff --git a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts index bac92589dc8..b06732ff85c 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithRedirect.ts @@ -37,6 +37,7 @@ import { listenForOAuthFlowCancellation } from '../utils/oauth/cancelOAuthFlow'; export async function signInWithRedirect( input?: SignInWithRedirectInput, ): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); assertOAuthConfig(authConfig); diff --git a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts index d2d9588f6bc..27c5719ee59 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithSRP.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithSRP.ts @@ -51,6 +51,7 @@ import { resetAutoSignIn } from './autoSignIn'; export async function signInWithSRP( input: SignInWithSRPInput, ): Promise { + Amplify.assertConfigured(); const { username, password } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; const signInDetails: CognitoAuthSignInDetails = { diff --git a/packages/auth/src/providers/cognito/apis/signInWithUserAuth.ts b/packages/auth/src/providers/cognito/apis/signInWithUserAuth.ts index 1b2957c9480..87278973ca2 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithUserAuth.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithUserAuth.ts @@ -55,6 +55,7 @@ import { resetAutoSignIn } from './autoSignIn'; export async function signInWithUserAuth( input: SignInWithUserAuthInput, ): Promise { + Amplify.assertConfigured(); const { username, password, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; const signInDetails: CognitoAuthSignInDetails = { diff --git a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts index e9280227a37..96dda3c3d5d 100644 --- a/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts +++ b/packages/auth/src/providers/cognito/apis/signInWithUserPassword.ts @@ -48,6 +48,7 @@ import { resetAutoSignIn } from './autoSignIn'; export async function signInWithUserPassword( input: SignInWithUserPasswordInput, ): Promise { + Amplify.assertConfigured(); const { username, password, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; const signInDetails: CognitoAuthSignInDetails = { diff --git a/packages/auth/src/providers/cognito/apis/signOut.ts b/packages/auth/src/providers/cognito/apis/signOut.ts index 2fa52b73ee4..fd9dda866e6 100644 --- a/packages/auth/src/providers/cognito/apis/signOut.ts +++ b/packages/auth/src/providers/cognito/apis/signOut.ts @@ -44,6 +44,7 @@ const logger = new ConsoleLogger('Auth'); * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signOut(input?: SignOutInput): Promise { + Amplify.assertConfigured(); const cognitoConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(cognitoConfig); diff --git a/packages/auth/src/providers/cognito/apis/signUp.ts b/packages/auth/src/providers/cognito/apis/signUp.ts index 2861541243c..3c8ea4c7ff8 100644 --- a/packages/auth/src/providers/cognito/apis/signUp.ts +++ b/packages/auth/src/providers/cognito/apis/signUp.ts @@ -40,6 +40,7 @@ import { setAutoSignIn } from './autoSignIn'; * @throws AuthTokenConfigException - Thrown when the token provider config is invalid. */ export async function signUp(input: SignUpInput): Promise { + Amplify.assertConfigured(); const { username, password, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; const signUpVerificationMethod = diff --git a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts index 200c9e59f0e..7ceb48adc9e 100644 --- a/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts +++ b/packages/auth/src/providers/cognito/apis/updateMFAPreference.ts @@ -27,6 +27,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export async function updateMFAPreference( input: UpdateMFAPreferenceInput, ): Promise { + Amplify.assertConfigured(); const { sms, totp, email } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); diff --git a/packages/auth/src/providers/cognito/apis/updatePassword.ts b/packages/auth/src/providers/cognito/apis/updatePassword.ts index f8c8c4bdeae..6e8ce3af845 100644 --- a/packages/auth/src/providers/cognito/apis/updatePassword.ts +++ b/packages/auth/src/providers/cognito/apis/updatePassword.ts @@ -28,6 +28,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export async function updatePassword( input: UpdatePasswordInput, ): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts index 5076e3145a5..97c71698b1b 100644 --- a/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts +++ b/packages/auth/src/providers/cognito/apis/updateUserAttributes.ts @@ -36,6 +36,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export const updateUserAttributes = async ( input: UpdateUserAttributesInput, ): Promise => { + Amplify.assertConfigured(); const { userAttributes, options } = input; const authConfig = Amplify.getConfig().Auth?.Cognito; const clientMetadata = options?.clientMetadata; diff --git a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts index c5c1212c194..9ec9dffde90 100644 --- a/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts +++ b/packages/auth/src/providers/cognito/apis/verifyTOTPSetup.ts @@ -30,6 +30,7 @@ import { createCognitoUserPoolEndpointResolver } from '../factories'; export async function verifyTOTPSetup( input: VerifyTOTPSetupInput, ): Promise { + Amplify.assertConfigured(); const authConfig = Amplify.getConfig().Auth?.Cognito; assertTokenProviderConfig(authConfig); const { userPoolEndpoint, userPoolId } = authConfig; diff --git a/packages/aws-amplify/package.json b/packages/aws-amplify/package.json index c1d334c53a3..e669d72ea42 100644 --- a/packages/aws-amplify/package.json +++ b/packages/aws-amplify/package.json @@ -310,7 +310,7 @@ "name": "[Analytics] record (Pinpoint)", "path": "./dist/esm/analytics/index.mjs", "import": "{ record }", - "limit": "17.63 kB" + "limit": "17.73 kB" }, { "name": "[Analytics] record (Kinesis)", @@ -334,7 +334,7 @@ "name": "[Analytics] identifyUser (Pinpoint)", "path": "./dist/esm/analytics/index.mjs", "import": "{ identifyUser }", - "limit": "16.14 kB" + "limit": "16.24 kB" }, { "name": "[Analytics] enable", @@ -370,25 +370,25 @@ "name": "[Auth] resetPassword (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ resetPassword }", - "limit": "12.71 kB" + "limit": "12.81 kB" }, { "name": "[Auth] confirmResetPassword (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ confirmResetPassword }", - "limit": "12.66 kB" + "limit": "12.76 kB" }, { "name": "[Auth] signIn (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ signIn }", - "limit": "28.78 kB" + "limit": "28.88 kB" }, { "name": "[Auth] resendSignUpCode (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ resendSignUpCode }", - "limit": "12.68 kB" + "limit": "12.78 kB" }, { "name": "[Auth] confirmSignUp (Cognito)", @@ -400,31 +400,31 @@ "name": "[Auth] confirmSignIn (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ confirmSignIn }", - "limit": "28.70 kB" + "limit": "28.80 kB" }, { "name": "[Auth] updateMFAPreference (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ updateMFAPreference }", - "limit": "12.15 kB" + "limit": "12.25 kB" }, { "name": "[Auth] fetchMFAPreference (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ fetchMFAPreference }", - "limit": "12.18 kB" + "limit": "12.28 kB" }, { "name": "[Auth] verifyTOTPSetup (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ verifyTOTPSetup }", - "limit": "13.02 kB" + "limit": "13.12 kB" }, { "name": "[Auth] updatePassword (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ updatePassword }", - "limit": "13.03 kB" + "limit": "13.13 kB" }, { "name": "[Auth] setUpTOTP (Cognito)", @@ -436,19 +436,19 @@ "name": "[Auth] updateUserAttributes (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ updateUserAttributes }", - "limit": "12.24 kB" + "limit": "12.34 kB" }, { "name": "[Auth] getCurrentUser (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ getCurrentUser }", - "limit": "8.09 kB" + "limit": "8.19 kB" }, { "name": "[Auth] confirmUserAttribute (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ confirmUserAttribute }", - "limit": "13.02 kB" + "limit": "13.12 kB" }, { "name": "[Auth] signInWithRedirect (Cognito)", @@ -460,13 +460,13 @@ "name": "[Auth] fetchUserAttributes (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ fetchUserAttributes }", - "limit": "12.07 kB" + "limit": "12.17 kB" }, { "name": "[Auth] Basic Auth Flow (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ signIn, signOut, fetchAuthSession, confirmSignIn }", - "limit": "31.00 kB" + "limit": "31.10 kB" }, { "name": "[Auth] OAuth Auth Flow (Cognito)", @@ -478,49 +478,49 @@ "name": "[Auth] Associate WebAuthN Credential (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ associateWebAuthnCredential }", - "limit": "13.59 kB" + "limit": "13.69 kB" }, { "name": "[Auth] List WebAuthN Credentials (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ listWebAuthnCredentials }", - "limit": "12.18 kB" + "limit": "12.28 kB" }, { "name": "[Auth] Delete WebAuthN Credential (Cognito)", "path": "./dist/esm/auth/index.mjs", "import": "{ deleteWebAuthnCredential }", - "limit": "12.04 kB" + "limit": "12.14 kB" }, { "name": "[Storage] copy (S3)", "path": "./dist/esm/storage/index.mjs", "import": "{ copy }", - "limit": "16.39 kB" + "limit": "16.46 kB" }, { "name": "[Storage] downloadData (S3)", "path": "./dist/esm/storage/index.mjs", "import": "{ downloadData }", - "limit": "16.73 kB" + "limit": "16.83 kB" }, { "name": "[Storage] getProperties (S3)", "path": "./dist/esm/storage/index.mjs", "import": "{ getProperties }", - "limit": "15.99 kB" + "limit": "16.05 kB" }, { "name": "[Storage] getUrl (S3)", "path": "./dist/esm/storage/index.mjs", "import": "{ getUrl }", - "limit": "17.22 kB" + "limit": "17.28 kB" }, { "name": "[Storage] list (S3)", "path": "./dist/esm/storage/index.mjs", "import": "{ list }", - "limit": "16.77 kB" + "limit": "16.92 kB" }, { "name": "[Storage] remove (S3)", @@ -532,7 +532,7 @@ "name": "[Storage] uploadData (S3)", "path": "./dist/esm/storage/index.mjs", "import": "{ uploadData }", - "limit": "23.00 kB" + "limit": "23.50 kB" } ] } diff --git a/packages/core/src/singleton/Amplify.ts b/packages/core/src/singleton/Amplify.ts index 76d4e5be9b4..8eaff1023a8 100644 --- a/packages/core/src/singleton/Amplify.ts +++ b/packages/core/src/singleton/Amplify.ts @@ -87,6 +87,21 @@ export class AmplifyClass { return this.resourcesConfig; } + /** + * Internal method to check if Amplify is configured + * Throws an error if Amplify hasn't been configured + * + * @internal + * @throws {Error} If Amplify.configure hasn't been called + */ + assertConfigured(): void { + if (Object.keys(this.resourcesConfig).length === 0) { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + } + } + /** @internal */ [ADD_OAUTH_LISTENER](listener: (authConfig: AuthConfig['Cognito']) => void) { if (this.resourcesConfig.Auth?.Cognito.loginWith?.oauth) { diff --git a/packages/geo/__tests__/Geo.test.ts b/packages/geo/__tests__/Geo.test.ts index a973e168436..6de44dacfeb 100644 --- a/packages/geo/__tests__/Geo.test.ts +++ b/packages/geo/__tests__/Geo.test.ts @@ -78,6 +78,7 @@ jest.mock('@aws-amplify/core', () => { fetchAuthSession: jest.fn(), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), }, }; }); diff --git a/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts b/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts index 506f0decf24..3da39cc6e1f 100644 --- a/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts +++ b/packages/geo/__tests__/Providers/AmazonLocationServiceProvider.test.ts @@ -77,6 +77,7 @@ jest.mock('@aws-amplify/core', () => { fetchAuthSession: jest.fn(), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), }, }; }); diff --git a/packages/geo/src/Geo.ts b/packages/geo/src/Geo.ts index 043c8ee32d1..793918d2c4a 100644 --- a/packages/geo/src/Geo.ts +++ b/packages/geo/src/Geo.ts @@ -38,7 +38,7 @@ export class GeoClass { constructor() { this._config = undefined; this._pluggables = []; - + Amplify.assertConfigured(); const amplifyConfig = Amplify.getConfig() ?? {}; this._config = Object.assign({}, this._config, amplifyConfig.Geo); diff --git a/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts b/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts index b5248d5ccbc..29cc2255e56 100644 --- a/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts +++ b/packages/geo/src/providers/location-service/AmazonLocationServiceProvider.ts @@ -730,6 +730,7 @@ export class AmazonLocationServiceProvider implements GeoProvider { } private _refreshConfig() { + Amplify.assertConfigured(); this._config = Amplify.getConfig().Geo?.LocationService; if (!this._config) { const errorString = diff --git a/packages/notifications/__tests__/pushNotifications/utils/resolveConfig.test.ts b/packages/notifications/__tests__/pushNotifications/utils/resolveConfig.test.ts index e30316ef425..43bd8ffcbb6 100644 --- a/packages/notifications/__tests__/pushNotifications/utils/resolveConfig.test.ts +++ b/packages/notifications/__tests__/pushNotifications/utils/resolveConfig.test.ts @@ -9,12 +9,27 @@ import { pinpointConfig } from '../../testUtils/data'; describe('resolveConfig', () => { // create spies const getConfigSpy = jest.spyOn(Amplify, 'getConfig'); + const assertConfiguredSpy = jest.spyOn(Amplify, 'assertConfigured'); - afterEach(() => { + beforeEach(() => { getConfigSpy.mockReset(); + assertConfiguredSpy.mockReset(); + }); + + it('throws if Amplify is not configured', () => { + assertConfiguredSpy.mockImplementation(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + expect(resolveConfig).toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); }); it('returns required config', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); getConfigSpy.mockReturnValue({ Notifications: { PushNotification: { Pinpoint: pinpointConfig }, @@ -24,6 +39,7 @@ describe('resolveConfig', () => { }); it('throws if appId is missing', () => { + assertConfiguredSpy.mockImplementation(jest.fn()); getConfigSpy.mockReturnValue({ Notifications: { PushNotification: { diff --git a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts index 4161066d0f8..1874b727926 100644 --- a/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts +++ b/packages/notifications/src/inAppMessaging/providers/pinpoint/utils/resolveConfig.ts @@ -12,6 +12,7 @@ import { * @internal */ export const resolveConfig = () => { + Amplify.assertConfigured(); const { appId, region } = Amplify.getConfig().Notifications?.InAppMessaging?.Pinpoint ?? {}; assertValidationError(!!appId, InAppMessagingValidationErrorCode.NoAppId); diff --git a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts index 65e08c82006..a14f117c998 100644 --- a/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts +++ b/packages/notifications/src/pushNotifications/providers/pinpoint/utils/resolveConfig.ts @@ -9,6 +9,7 @@ import { PushNotificationValidationErrorCode, assert } from '../../../errors'; * @internal */ export const resolveConfig = () => { + Amplify.assertConfigured(); const { appId, region } = Amplify.getConfig().Notifications?.PushNotification?.Pinpoint ?? {}; assert(!!appId, PushNotificationValidationErrorCode.NoAppId); diff --git a/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts b/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts index 5678c1b079c..92571f2cc8e 100644 --- a/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts +++ b/packages/predictions/__tests__/providers/AWSAIConvertPredictionsProvider.test.ts @@ -28,6 +28,7 @@ jest.mock('@aws-amplify/core', () => ({ fetchAuthSession: jest.fn(), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), }, ConsoleLogger: jest.fn(() => ({ debug: jest.fn(), diff --git a/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts b/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts index 042ca5c7114..febdea35ce8 100644 --- a/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts +++ b/packages/predictions/__tests__/providers/AWSAIIdentifyPredictionsProvider.test.ts @@ -48,6 +48,7 @@ jest.mock('@aws-amplify/core', () => ({ fetchAuthSession: jest.fn(), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), }, ConsoleLogger: jest.fn(() => ({ debug: jest.fn(), diff --git a/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts b/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts index 60bc46c4c2e..d9ab75e943f 100644 --- a/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts +++ b/packages/predictions/__tests__/providers/AWSAIInterpretPredictionsProvider.test.ts @@ -20,6 +20,7 @@ jest.mock('@aws-amplify/core', () => ({ fetchAuthSession: jest.fn(), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), }, ConsoleLogger: jest.fn(() => ({ debug: jest.fn(), diff --git a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts index 9b24de59b74..25a5d96e2a3 100644 --- a/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIConvertPredictionsProvider.ts @@ -81,6 +81,7 @@ export class AmazonAIConvertPredictionsProvider { protected async translateText( input: TranslateTextInput, ): Promise { + Amplify.assertConfigured(); logger.debug('Starting translation'); const { translateText = {} } = @@ -135,6 +136,7 @@ export class AmazonAIConvertPredictionsProvider { protected async convertTextToSpeech( input: TextToSpeechInput, ): Promise { + Amplify.assertConfigured(); const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, @@ -190,6 +192,7 @@ export class AmazonAIConvertPredictionsProvider { protected async convertSpeechToText( input: SpeechToTextInput, ): Promise { + Amplify.assertConfigured(); logger.debug('starting transcription..'); const { credentials } = await fetchAuthSession(); assertValidationError( diff --git a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts index 2ada5dd00a6..7eb498bcc1e 100644 --- a/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIIdentifyPredictionsProvider.ts @@ -166,6 +166,7 @@ export class AmazonAIIdentifyPredictionsProvider { protected async identifyText( input: IdentifyTextInput, ): Promise { + Amplify.assertConfigured(); const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, @@ -258,6 +259,7 @@ export class AmazonAIIdentifyPredictionsProvider { protected async identifyLabels( input: IdentifyLabelsInput, ): Promise { + Amplify.assertConfigured(); const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, @@ -360,6 +362,7 @@ export class AmazonAIIdentifyPredictionsProvider { protected async identifyEntities( input: IdentifyEntitiesInput, ): Promise { + Amplify.assertConfigured(); const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, diff --git a/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts b/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts index 537fc083c3b..7f3a4334806 100644 --- a/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts +++ b/packages/predictions/src/providers/AmazonAIInterpretPredictionsProvider.ts @@ -53,6 +53,7 @@ export class AmazonAIInterpretPredictionsProvider { } async interpretText(input: InterpretTextInput): Promise { + Amplify.assertConfigured(); const { credentials } = await fetchAuthSession(); assertValidationError( !!credentials, diff --git a/packages/storage/__tests__/providers/s3/apis/internal/copy.test.ts b/packages/storage/__tests__/providers/s3/apis/internal/copy.test.ts index 51b0e65fa79..08802bf671f 100644 --- a/packages/storage/__tests__/providers/s3/apis/internal/copy.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/internal/copy.test.ts @@ -24,6 +24,7 @@ jest.mock('@aws-amplify/core', () => ({ }), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), Auth: { fetchAuthSession: jest.fn(), }, @@ -438,6 +439,22 @@ describe('copy API', () => { afterEach(() => { jest.clearAllMocks(); }); + + it('throws if Amplify is not configured', async () => { + (Amplify.assertConfigured as jest.Mock).mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + await expect( + copy(Amplify, { + source: { key: 'sourceKey' }, + destination: { key: 'destinationKey' }, + }), + ).rejects.toThrow('Amplify has not been configured'); + }); + it('should return a not found error', async () => { mockCopyObject.mockRejectedValueOnce( Object.assign(new Error(), { diff --git a/packages/storage/__tests__/providers/s3/apis/internal/downloadData.test.ts b/packages/storage/__tests__/providers/s3/apis/internal/downloadData.test.ts index cb0dafdaf27..263afbbc093 100644 --- a/packages/storage/__tests__/providers/s3/apis/internal/downloadData.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/internal/downloadData.test.ts @@ -34,6 +34,7 @@ jest.mock('@aws-amplify/core', () => ({ }), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), Auth: { fetchAuthSession: jest.fn(), }, @@ -544,4 +545,26 @@ describe('downloadData with path', () => { ); }); }); + + describe('Error cases', () => { + it('throws if Amplify is not configured', async () => { + // Set up the error + (Amplify.assertConfigured as jest.Mock).mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + // Get the task creation arguments + downloadData({ key: 'testKey' }); + + // Get the job function that was passed to createDownloadTask + const { job } = mockCreateDownloadTask.mock.calls[0][0]; + + // Test that the job throws when executed + await expect(job()).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + }); }); diff --git a/packages/storage/__tests__/providers/s3/apis/internal/getProperties.test.ts b/packages/storage/__tests__/providers/s3/apis/internal/getProperties.test.ts index 01d7a73ef2c..d682298fdaf 100644 --- a/packages/storage/__tests__/providers/s3/apis/internal/getProperties.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/internal/getProperties.test.ts @@ -22,6 +22,7 @@ jest.mock('@aws-amplify/core', () => ({ }), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), Auth: { fetchAuthSession: jest.fn(), }, @@ -212,6 +213,21 @@ describe('getProperties with key', () => { afterEach(() => { jest.clearAllMocks(); }); + it('throws if Amplify is not configured', async () => { + // Mock assertConfigured to throw an error just for this test + (Amplify.assertConfigured as jest.Mock).mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + // Use expect to assert that the remove function throws the expected error + await expect( + getProperties(Amplify, { path: 'testPath' }), + ).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); it('getProperties should return a not found error', async () => { mockHeadObject.mockRejectedValueOnce( Object.assign(new Error(), { diff --git a/packages/storage/__tests__/providers/s3/apis/internal/getUrl.test.ts b/packages/storage/__tests__/providers/s3/apis/internal/getUrl.test.ts index 03ade454d44..d92950ce46b 100644 --- a/packages/storage/__tests__/providers/s3/apis/internal/getUrl.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/internal/getUrl.test.ts @@ -23,6 +23,7 @@ jest.mock('@aws-amplify/core', () => ({ }), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), Auth: { fetchAuthSession: jest.fn(), }, @@ -187,6 +188,19 @@ describe('getUrl test with key', () => { afterAll(() => { jest.clearAllMocks(); }); + it('throws if Amplify is not configured', async () => { + // Mock assertConfigured to throw an error just for this test + (Amplify.assertConfigured as jest.Mock).mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + // Use expect to assert that the remove function throws the expected error + await expect(getUrl(Amplify, { path: 'testPath' })).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); it('should return not found error when the object is not found', async () => { (headObject as jest.Mock).mockImplementation(() => { throw Object.assign(new Error(), { diff --git a/packages/storage/__tests__/providers/s3/apis/internal/list.test.ts b/packages/storage/__tests__/providers/s3/apis/internal/list.test.ts index e861652a90e..335b214dea1 100644 --- a/packages/storage/__tests__/providers/s3/apis/internal/list.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/internal/list.test.ts @@ -25,6 +25,7 @@ jest.mock('@aws-amplify/core', () => ({ }), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), Auth: { fetchAuthSession: jest.fn(), }, @@ -650,6 +651,21 @@ describe('list API', () => { afterEach(() => { jest.clearAllMocks(); }); + + it('throws if Amplify is not configured', async () => { + // Mock assertConfigured to throw an error just for this test + (Amplify.assertConfigured as jest.Mock).mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + // Use expect to assert that the remove function throws the expected error + await expect(list(Amplify, {})).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + it('should return a not found error', async () => { mockListObject.mockRejectedValueOnce( Object.assign(new Error(), { diff --git a/packages/storage/__tests__/providers/s3/apis/internal/remove.test.ts b/packages/storage/__tests__/providers/s3/apis/internal/remove.test.ts index 6db2fcb997a..06b354ac022 100644 --- a/packages/storage/__tests__/providers/s3/apis/internal/remove.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/internal/remove.test.ts @@ -22,6 +22,7 @@ jest.mock('@aws-amplify/core', () => ({ }), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), Auth: { fetchAuthSession: jest.fn(), }, @@ -300,6 +301,21 @@ describe('remove API', () => { afterEach(() => { jest.clearAllMocks(); }); + + it('throws if Amplify is not configured', async () => { + // Mock assertConfigured to throw an error just for this test + (Amplify.assertConfigured as jest.Mock).mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + // Use expect to assert that the remove function throws the expected error + await expect(remove(Amplify, { key: 'testKey' })).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + it('should return a not found error', async () => { mockDeleteObject.mockRejectedValueOnce( Object.assign(new Error(), { diff --git a/packages/storage/__tests__/providers/s3/apis/internal/uploadData/putObjectJob.test.ts b/packages/storage/__tests__/providers/s3/apis/internal/uploadData/putObjectJob.test.ts index 2665fdef227..33252b0aab0 100644 --- a/packages/storage/__tests__/providers/s3/apis/internal/uploadData/putObjectJob.test.ts +++ b/packages/storage/__tests__/providers/s3/apis/internal/uploadData/putObjectJob.test.ts @@ -26,6 +26,7 @@ jest.mock('@aws-amplify/core', () => ({ fetchAuthSession: jest.fn(), Amplify: { getConfig: jest.fn(), + assertConfigured: jest.fn(), Auth: { fetchAuthSession: jest.fn(), }, @@ -454,4 +455,33 @@ describe('putObjectJob with path', () => { ); }); }); + + describe('Error tests', () => { + beforeEach(() => { + mockPutObject.mockClear(); + jest.spyOn(CRC32, 'calculateContentCRC32').mockRestore(); + }); + + // Add at the beginning of the describe block + it('throws if Amplify is not configured', async () => { + (Amplify.assertConfigured as jest.Mock).mockImplementationOnce(() => { + throw new Error( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + + const job = putObjectJob( + { + key: 'testKey', + data: 'testData', + }, + new AbortController().signal, + 'testData'.length, + ); + + await expect(job()).rejects.toThrow( + 'Amplify has not been configured. Please call Amplify.configure() before using this service.', + ); + }); + }); }); diff --git a/packages/storage/src/providers/s3/apis/internal/copy.ts b/packages/storage/src/providers/s3/apis/internal/copy.ts index 85898ea228f..a89b7709ba9 100644 --- a/packages/storage/src/providers/s3/apis/internal/copy.ts +++ b/packages/storage/src/providers/s3/apis/internal/copy.ts @@ -58,6 +58,7 @@ const copyWithPath = async ( amplify: AmplifyClassV6, input: CopyWithPathInputWithAdvancedOptions, ): Promise => { + amplify.assertConfigured(); const { source, destination } = input; storageBucketAssertion(source.bucket, destination.bucket); @@ -124,6 +125,7 @@ export const copyWithKey = async ( amplify: AmplifyClassV6, input: CopyInput, ): Promise => { + amplify.assertConfigured(); const { source, destination } = input; storageBucketAssertion(source.bucket, destination.bucket); diff --git a/packages/storage/src/providers/s3/apis/internal/downloadData.ts b/packages/storage/src/providers/s3/apis/internal/downloadData.ts index f1d804b323d..6a4d0741796 100644 --- a/packages/storage/src/providers/s3/apis/internal/downloadData.ts +++ b/packages/storage/src/providers/s3/apis/internal/downloadData.ts @@ -45,6 +45,7 @@ const downloadDataJob = async (): Promise< StorageDownloadDataOutput > => { + Amplify.assertConfigured(); const { options: downloadDataOptions } = downloadDataInput; const { bucket, keyPrefix, s3Config, identityId } = await resolveS3ConfigAndInput(Amplify, downloadDataInput); diff --git a/packages/storage/src/providers/s3/apis/internal/getProperties.ts b/packages/storage/src/providers/s3/apis/internal/getProperties.ts index 981c32cb827..d0b2dc2a432 100644 --- a/packages/storage/src/providers/s3/apis/internal/getProperties.ts +++ b/packages/storage/src/providers/s3/apis/internal/getProperties.ts @@ -26,6 +26,7 @@ export const getProperties = async ( input: GetPropertiesInput | GetPropertiesWithPathInputWithAdvancedOptions, action?: StorageAction, ): Promise => { + amplify.assertConfigured(); const { s3Config, bucket, keyPrefix, identityId } = await resolveS3ConfigAndInput(amplify, input); const { inputType, objectKey } = validateStorageOperationInput( diff --git a/packages/storage/src/providers/s3/apis/internal/getUrl.ts b/packages/storage/src/providers/s3/apis/internal/getUrl.ts index db2315ddb78..06b2ae6fada 100644 --- a/packages/storage/src/providers/s3/apis/internal/getUrl.ts +++ b/packages/storage/src/providers/s3/apis/internal/getUrl.ts @@ -28,6 +28,7 @@ export const getUrl = async ( amplify: AmplifyClassV6, input: GetUrlInput | GetUrlWithPathInputWithAdvancedOptions, ): Promise => { + amplify.assertConfigured(); const { options: getUrlOptions } = input; const { s3Config, keyPrefix, bucket, identityId } = await resolveS3ConfigAndInput(amplify, input); diff --git a/packages/storage/src/providers/s3/apis/internal/list.ts b/packages/storage/src/providers/s3/apis/internal/list.ts index ef8d277b48d..d8d00c8a111 100644 --- a/packages/storage/src/providers/s3/apis/internal/list.ts +++ b/packages/storage/src/providers/s3/apis/internal/list.ts @@ -54,6 +54,7 @@ export const list = async ( | ListAllWithPathOutput | ListPaginateWithPathOutput > => { + amplify.assertConfigured(); const { options = {} } = input; const { s3Config, diff --git a/packages/storage/src/providers/s3/apis/internal/remove.ts b/packages/storage/src/providers/s3/apis/internal/remove.ts index e751b6bbb61..dd0048d5d38 100644 --- a/packages/storage/src/providers/s3/apis/internal/remove.ts +++ b/packages/storage/src/providers/s3/apis/internal/remove.ts @@ -21,6 +21,7 @@ export const remove = async ( amplify: AmplifyClassV6, input: RemoveInput | RemoveWithPathInputWithAdvancedOptions, ): Promise => { + amplify.assertConfigured(); const { s3Config, keyPrefix, bucket, identityId } = await resolveS3ConfigAndInput(amplify, input); diff --git a/packages/storage/src/providers/s3/apis/internal/uploadData/putObjectJob.ts b/packages/storage/src/providers/s3/apis/internal/uploadData/putObjectJob.ts index 340cd5d610a..b6e79a239e2 100644 --- a/packages/storage/src/providers/s3/apis/internal/uploadData/putObjectJob.ts +++ b/packages/storage/src/providers/s3/apis/internal/uploadData/putObjectJob.ts @@ -46,6 +46,7 @@ export const putObjectJob = totalLength: number, ) => async (): Promise => { + Amplify.assertConfigured(); const { options: uploadDataOptions, data } = uploadDataInput; const { bucket, keyPrefix, s3Config, isObjectLockEnabled, identityId } = await resolveS3ConfigAndInput(Amplify, uploadDataInput);