UNPKG

@clerk/testing

Version:

Utilities to help you create E2E test suites for apps using Clerk

1 lines 7.74 kB
{"version":3,"sources":["../src/common/setup.ts","../src/common/helpers-utils.ts"],"sourcesContent":["import { createClerkClient } from '@clerk/backend';\nimport { isProductionFromSecretKey, parsePublishableKey } from '@clerk/shared/keys';\nimport dotenv from 'dotenv';\n\nimport type { ClerkSetupOptions, ClerkSetupReturn } from './types';\n\nexport const fetchEnvVars = async (options?: ClerkSetupOptions): Promise<ClerkSetupReturn> => {\n const { debug = false, dotenv: loadDotEnv = true, ...rest } = options || {};\n\n const log = (msg: string) => {\n if (debug) {\n console.log(`Clerk: ${msg}`);\n }\n };\n\n log('Setting up Clerk...');\n\n if (loadDotEnv) {\n dotenv.config({ path: ['.env.local', '.env'] });\n }\n\n const publishableKey =\n rest.publishableKey ||\n process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY ||\n process.env.VITE_CLERK_PUBLISHABLE_KEY ||\n process.env.CLERK_PUBLISHABLE_KEY ||\n process.env.REACT_APP_CLERK_PUBLISHABLE_KEY ||\n process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY;\n\n const secretKey = rest.secretKey || process.env.CLERK_SECRET_KEY;\n let testingToken = process.env.CLERK_TESTING_TOKEN;\n\n if (!publishableKey) {\n throw new Error('You need to set the CLERK_PUBLISHABLE_KEY environment variable.');\n }\n\n if (!secretKey && !testingToken) {\n throw new Error('You need to set the CLERK_SECRET_KEY or the CLERK_TESTING_TOKEN environment variable.');\n }\n\n if (secretKey && !testingToken) {\n if (isProductionFromSecretKey(secretKey)) {\n throw new Error(\n 'You are using a secret key from a production instance, but Testing Tokens only work in development instances.',\n );\n }\n\n log('Fetching testing token from Clerk Backend API...');\n\n try {\n const apiUrl = (rest as any)?.apiUrl || process.env.CLERK_API_URL;\n const clerkClient = createClerkClient({ secretKey, apiUrl });\n const tokenData = await clerkClient.testingTokens.createTestingToken();\n testingToken = tokenData.token;\n } catch (err) {\n console.error('Failed to fetch testing token from Clerk API.');\n throw err;\n }\n }\n\n return {\n CLERK_FAPI: options?.frontendApiUrl || parsePublishableKey(publishableKey)?.frontendApi,\n CLERK_TESTING_TOKEN: testingToken,\n };\n};\n","import type { EmailCodeFactor, PhoneCodeFactor, SignInFirstFactor } from '@clerk/types';\n\nimport type { SignInHelperParams } from './types';\n\n// This function is serialized and executed in the browser context\nexport const signInHelper = async ({ signInParams, windowObject }: SignInHelperParams) => {\n try {\n const w = windowObject || window;\n if (!w.Clerk.client) {\n return;\n }\n const signIn = w.Clerk.client.signIn;\n if (signInParams.strategy === 'password') {\n const res = await signIn.create(signInParams);\n await w.Clerk.setActive({\n session: res.createdSessionId,\n });\n } else {\n // Assert that the identifier is a test email or phone number\n if (signInParams.strategy === 'phone_code' && !/^\\+1\\d{3}55501\\d{2}$/.test(signInParams.identifier)) {\n throw new Error(\n `Phone number should be a test phone number.\\n\n Example: +1XXX55501XX.\\n\n Learn more here: https://clerk.com/docs/testing/test-emails-and-phones#phone-numbers`,\n );\n }\n if (signInParams.strategy === 'email_code' && !signInParams.identifier.includes('+clerk_test')) {\n throw new Error(\n `Email should be a test email.\\n\n Any email with the +clerk_test subaddress is a test email address.\\n\n Learn more here: https://clerk.com/docs/testing/test-emails-and-phones#email-addresses`,\n );\n }\n\n // Sign in with code (email_code or phone_code)\n const { supportedFirstFactors } = await signIn.create({\n identifier: signInParams.identifier,\n });\n const codeFactorFn =\n signInParams.strategy === 'phone_code'\n ? (factor: SignInFirstFactor): factor is PhoneCodeFactor => factor.strategy === 'phone_code'\n : (factor: SignInFirstFactor): factor is EmailCodeFactor => factor.strategy === 'email_code';\n const codeFactor = supportedFirstFactors?.find(codeFactorFn);\n if (codeFactor) {\n const prepareParams =\n signInParams.strategy === 'phone_code'\n ? { strategy: signInParams.strategy, phoneNumberId: (codeFactor as PhoneCodeFactor).phoneNumberId }\n : { strategy: signInParams.strategy, emailAddressId: (codeFactor as EmailCodeFactor).emailAddressId };\n\n await signIn.prepareFirstFactor(prepareParams);\n const signInAttempt = await signIn.attemptFirstFactor({\n strategy: signInParams.strategy,\n code: '424242',\n });\n\n if (signInAttempt.status === 'complete') {\n await w.Clerk.setActive({ session: signInAttempt.createdSessionId });\n } else {\n throw new Error(`Status is ${signInAttempt.status}`);\n }\n } else {\n throw new Error(`${signInParams.strategy} is not enabled.`);\n }\n }\n } catch (err: any) {\n throw new Error(`Clerk: Failed to sign in: ${err?.message}`);\n }\n};\n"],"mappings":"AAAA,OAAS,qBAAAA,MAAyB,iBAClC,OAAS,6BAAAC,EAA2B,uBAAAC,MAA2B,qBAC/D,OAAOC,MAAY,SAIZ,IAAMC,EAAe,MAAOC,GAA2D,CAC5F,GAAM,CAAE,MAAAC,EAAQ,GAAO,OAAQC,EAAa,GAAM,GAAGC,CAAK,EAAIH,GAAW,CAAC,EAEpEI,EAAOC,GAAgB,CACvBJ,GACF,QAAQ,IAAI,UAAUI,CAAG,EAAE,CAE/B,EAEAD,EAAI,qBAAqB,EAErBF,GACFJ,EAAO,OAAO,CAAE,KAAM,CAAC,aAAc,MAAM,CAAE,CAAC,EAGhD,IAAMQ,EACJH,EAAK,gBACL,QAAQ,IAAI,mCACZ,QAAQ,IAAI,4BACZ,QAAQ,IAAI,uBACZ,QAAQ,IAAI,iCACZ,QAAQ,IAAI,kCAERI,EAAYJ,EAAK,WAAa,QAAQ,IAAI,iBAC5CK,EAAe,QAAQ,IAAI,oBAE/B,GAAI,CAACF,EACH,MAAM,IAAI,MAAM,iEAAiE,EAGnF,GAAI,CAACC,GAAa,CAACC,EACjB,MAAM,IAAI,MAAM,uFAAuF,EAGzG,GAAID,GAAa,CAACC,EAAc,CAC9B,GAAIZ,EAA0BW,CAAS,EACrC,MAAM,IAAI,MACR,+GACF,EAGFH,EAAI,kDAAkD,EAEtD,GAAI,CACF,IAAMK,EAAUN,GAAc,QAAU,QAAQ,IAAI,cAGpDK,GADkB,MADEb,EAAkB,CAAE,UAAAY,EAAW,OAAAE,CAAO,CAAC,EACvB,cAAc,m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AAc,SAAW,WAC3B,MAAMR,EAAE,MAAM,UAAU,CAAE,QAASQ,EAAc,gBAAiB,CAAC,MAEnE,OAAM,IAAI,MAAM,aAAaA,EAAc,MAAM,EAAE,CAEvD,KACE,OAAM,IAAI,MAAM,GAAGV,EAAa,QAAQ,kBAAkB,CAE9D,CACF,OAASW,EAAU,CACjB,MAAM,IAAI,MAAM,6BAA6BA,GAAK,OAAO,EAAE,CAC7D,CACF","names":["createClerkClient","isProductionFromSecretKey","parsePublishableKey","dotenv","fetchEnvVars","options","debug","loadDotEnv","rest","log","msg","publishableKey","secretKey","testingToken","apiUrl","err","signInHelper","signInParams","windowObject","w","signIn","res","supportedFirstFactors","codeFactorFn","factor","codeFactor","prepareParams","signInAttempt","err"]}