Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
test(mobile): add auth provider and sign-in tests
Richie McIlroy0ea7baa31a10
diff --git a/apps/mobile/src/auth/AuthProvider.test.tsx b/apps/mobile/src/auth/AuthProvider.test.tsxindex 0d9c232f2..05f98ea89 100644--- a/apps/mobile/src/auth/AuthProvider.test.tsx+++ b/apps/mobile/src/auth/AuthProvider.test.tsx@@ -8,6 +8,7 @@ type HostProps = {};const secureStoreMock = vi.hoisted(() => ({+ WHEN_UNLOCKED_THIS_DEVICE_ONLY: "whenUnlockedThisDeviceOnly",deleteItemAsync: vi.fn((_key: string) => Promise.resolve()),getItemAsync: vi.fn((_key: string) => Promise.resolve(null as string | null)),setItemAsync: vi.fn((_key: string, _value: string) => Promise.resolve()),@@ -25,10 +26,19 @@ const apiMock = vi.hoisted(() => ({),getAuthConfig: vi.fn(() =>Promise.resolve({+ appleAuthAvailable: true,googleAuthAvailable: true,workosAuthAvailable: true,}),),+ createSessionRequestUrl: vi.fn(+ () => "https://cap.so/api/mobile/session/request",+ ),+}));++const webBrowserMock = vi.hoisted(() => ({+ maybeCompleteAuthSession: vi.fn(),+ openAuthSessionAsync: vi.fn(),}));vi.mock("react-native", async () => {@@ -54,10 +64,7 @@ vi.mock("expo-linking", () => ({vi.mock("expo-secure-store", () => secureStoreMock);-vi.mock("expo-web-browser", () => ({- maybeCompleteAuthSession: vi.fn(),- openAuthSessionAsync: vi.fn(),-}));+vi.mock("expo-web-browser", () => webBrowserMock);vi.mock("@/api/mobile", () => ({createMobileApiClient: vi.fn(() => ({@@ -66,9 +73,7 @@ vi.mock("@/api/mobile", () => ({revokeSession: vi.fn(() => Promise.resolve({ success: true })),setActiveOrganization: vi.fn(),})),- createSessionRequestUrl: vi.fn(- () => "https://cap.so/api/mobile/session/request",- ),+ createSessionRequestUrl: apiMock.createSessionRequestUrl,}));(@@ -88,8 +93,11 @@ const states: Array<{userId: string | null;}> = [];+let latestAuth: ReturnType<typeof useAuth> | null = null;+const Probe = () => {const auth = useAuth();+ latestAuth = auth;states.push({apiKey: auth.apiKey,status: auth.status,@@ -101,6 +109,7 @@ const Probe = () => {describe("AuthProvider", () => {beforeEach(() => {states.length = 0;+ latestAuth = null;secureStoreMock.deleteItemAsync.mockClear();secureStoreMock.getItemAsync.mockReset();secureStoreMock.getItemAsync.mockResolvedValue(null);@@ -115,9 +124,82 @@ describe("AuthProvider", () => {});apiMock.getAuthConfig.mockReset();apiMock.getAuthConfig.mockResolvedValue({+ appleAuthAvailable: true,googleAuthAvailable: true,workosAuthAvailable: true,});+ apiMock.createSessionRequestUrl.mockClear();+ webBrowserMock.openAuthSessionAsync.mockReset();+ });++ it("stores a mobile session returned by Sign in with Apple", async () => {+ webBrowserMock.openAuthSessionAsync.mockResolvedValueOnce({+ type: "success",+ url: "cap://auth?api_key=apple_key&user_id=apple_user",+ });++ await act(async () => {+ TestRenderer.create(+ React.createElement(AuthProvider, null, React.createElement(Probe)),+ );+ await flushMicrotasks();+ });+ await act(async () => {+ await latestAuth?.signInWithApple();+ await flushMicrotasks();+ });++ expect(apiMock.createSessionRequestUrl).toHaveBeenCalledWith(+ "https://cap.so",+ "cap://auth",+ "apple",+ );+ expect(webBrowserMock.openAuthSessionAsync).toHaveBeenCalledWith(+ "https://cap.so/api/mobile/session/request",+ "cap://auth",+ );+ expect(secureStoreMock.setItemAsync).toHaveBeenCalledWith(+ "cap.mobile.apiKey",+ "apple_key",+ {+ keychainAccessible: "whenUnlockedThisDeviceOnly",+ },+ );+ expect(secureStoreMock.setItemAsync).toHaveBeenCalledWith(+ "cap.mobile.userId",+ "apple_user",+ {+ keychainAccessible: "whenUnlockedThisDeviceOnly",+ },+ );+ expect(states.at(-1)).toMatchObject({+ apiKey: "apple_key",+ status: "signedIn",+ userId: "apple_user",+ });+ });++ it("leaves the user signed out when Apple authentication is cancelled", async () => {+ webBrowserMock.openAuthSessionAsync.mockResolvedValueOnce({+ type: "cancel",+ });++ await act(async () => {+ TestRenderer.create(+ React.createElement(AuthProvider, null, React.createElement(Probe)),+ );+ await flushMicrotasks();+ });+ await act(async () => {+ await latestAuth?.signInWithApple();+ });++ expect(secureStoreMock.setItemAsync).not.toHaveBeenCalled();+ expect(states.at(-1)).toMatchObject({+ apiKey: null,+ status: "signedOut",+ userId: null,+ });});it("clears an orphaned stored user id when no API key is stored", async () => {diff --git a/apps/mobile/src/auth/SignInPanel.test.tsx b/apps/mobile/src/auth/SignInPanel.test.tsxindex 9970dfb9c..54ddee082 100644--- a/apps/mobile/src/auth/SignInPanel.test.tsx+++ b/apps/mobile/src/auth/SignInPanel.test.tsx@@ -16,15 +16,21 @@ type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;const authFns = vi.hoisted(() => ({authConfig: {+ appleAuthAvailable: true,googleAuthAvailable: true,workosAuthAvailable: true,},requestEmailCode: vi.fn(() => Promise.resolve()),+ signInWithApple: vi.fn(),signInWithGoogle: vi.fn(),signInWithSso: vi.fn(),verifyEmailCode: vi.fn(),}));+const appleAuthenticationFns = vi.hoisted(() => ({+ isAvailableAsync: vi.fn(() => Promise.resolve(true)),+}));+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -119,6 +125,25 @@ vi.mock("expo-symbols", () => ({SymbolView: () => null,}));+vi.mock("expo-apple-authentication", async () => {+ const React = await import("react");+ return {+ AppleAuthenticationButton: (props: HostProps) =>+ React.createElement(+ "AppleAuthenticationButton",+ props,+ "Sign in with Apple",+ ),+ AppleAuthenticationButtonStyle: {+ BLACK: 0,+ },+ AppleAuthenticationButtonType: {+ SIGN_IN: 0,+ },+ isAvailableAsync: appleAuthenticationFns.isAvailableAsync,+ };+});+vi.mock("expo-web-browser", () => ({openBrowserAsync: vi.fn(),}));@@ -148,6 +173,7 @@ vi.mock("@/auth/AuthContext", () => ({useAuth: () => ({authConfig: authFns.authConfig,requestEmailCode: authFns.requestEmailCode,+ signInWithApple: authFns.signInWithApple,signInWithGoogle: authFns.signInWithGoogle,signInWithSso: authFns.signInWithSso,verifyEmailCode: authFns.verifyEmailCode,@@ -169,12 +195,17 @@ vi.mock("@/api/mobile", () => ({describe("SignInPanel", () => {beforeEach(() => {+ appleAuthenticationFns.isAvailableAsync.mockReset();+ appleAuthenticationFns.isAvailableAsync.mockResolvedValue(true);+ authFns.authConfig.appleAuthAvailable = true;authFns.authConfig.googleAuthAvailable = true;authFns.authConfig.workosAuthAvailable = true;authFns.requestEmailCode.mockReset();authFns.requestEmailCode.mockResolvedValue(undefined);authFns.verifyEmailCode.mockReset();authFns.verifyEmailCode.mockResolvedValue(undefined);+ authFns.signInWithApple.mockReset();+ authFns.signInWithApple.mockResolvedValue(undefined);authFns.signInWithGoogle.mockReset();authFns.signInWithGoogle.mockResolvedValue(undefined);authFns.signInWithSso.mockReset();@@ -215,6 +246,7 @@ describe("SignInPanel", () => {).toBe(true);expect(hasProp(tree, "accessibilityRole", "link")).toBe(true);expect(text).toContain("OR");+ expect(text).toContain("Sign in with Apple");expect(text).toContain("Login with Google");expect(text).toContain("Login with SAML SSO");expect(text).toContain("Terms of Service");@@ -236,6 +268,7 @@ describe("SignInPanel", () => {});it("hides unavailable provider options", async () => {+ authFns.authConfig.appleAuthAvailable = false;authFns.authConfig.googleAuthAvailable = false;authFns.authConfig.workosAuthAvailable = false;@@ -244,10 +277,22 @@ describe("SignInPanel", () => {expect(text).toContain("Login with email");expect(text).not.toContain("OR");+ expect(text).not.toContain("Sign in with Apple");expect(text).not.toContain("Login with Google");expect(text).not.toContain("Login with SAML SSO");});+ it("hides Apple sign in when native authentication is unavailable", async () => {+ appleAuthenticationFns.isAvailableAsync.mockResolvedValueOnce(false);++ const tree = await renderTree(React.createElement(SignInPanel));+ const text = getTextNodes(tree);++ expect(text).not.toContain("Sign in with Apple");+ expect(text).toContain("Login with Google");+ expect(text).toContain("Login with SAML SSO");+ });+it("shows the native SSO organization step", async () => {const renderer = await renderPanel();const [ssoButton] = renderer.root.findAllByProps({@@ -577,6 +622,9 @@ describe("SignInPanel", () => {const [emailButton] = renderer.root.findAllByProps({accessibilityLabel: "Login with email",});+ const [appleButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Sign in with Apple",+ });const [googleButton] = renderer.root.findAllByProps({accessibilityLabel: "Login with Google",});@@ -594,6 +642,7 @@ describe("SignInPanel", () => {});if (!emailButton ||+ !appleButton ||!googleButton ||!ssoButton ||!signupLink ||@@ -619,6 +668,16 @@ describe("SignInPanel", () => {const [loadingSsoButton] = renderer.root.findAllByProps({accessibilityLabel: "Login with SAML SSO",});+ const [loadingAppleButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Sign in with Apple",+ });+ expect(loadingAppleButton?.props.accessibilityState).toEqual({+ busy: false,+ disabled: true,+ });+ expect(loadingAppleButton?.props.accessibilityValue).toEqual({+ text: "Starting Google sign in",+ });expect(loadingEmailButton?.props.disabled).toBe(true);expect(loadingEmailButton?.props.accessibilityHint).toBe("Sign in is in progress",@@ -651,6 +710,7 @@ describe("SignInPanel", () => {openBrowserAsync.mockClear();await act(async () => {+ appleButton.props.onPress();googleButton.props.onPress();emailButton.props.onPress();ssoButton.props.onPress();@@ -660,6 +720,7 @@ describe("SignInPanel", () => {await Promise.resolve();});+ expect(authFns.signInWithApple).not.toHaveBeenCalled();expect(authFns.signInWithGoogle).toHaveBeenCalledTimes(1);expect(authFns.requestEmailCode).not.toHaveBeenCalled();expect(openBrowserAsync).not.toHaveBeenCalled();@@ -715,6 +776,37 @@ describe("SignInPanel", () => {).toHaveLength(0);});+ it("keeps a failed Apple sign-in retryable on the system button", async () => {+ authFns.signInWithApple.mockRejectedValueOnce(+ new Error("Apple unavailable"),+ );+ const renderer = await renderPanel();+ const [appleButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Sign in with Apple",+ });+ if (!appleButton) throw new Error("Apple button was not rendered");++ await act(async () => {+ await appleButton.props.onPress();+ });++ expect(getTextNodes(renderer.toJSON())).toContain("Apple unavailable");+ const [retryAppleButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Sign in with Apple",+ });+ expect(retryAppleButton?.props.accessibilityHint).toBe("Apple unavailable");+ expect(retryAppleButton?.props.accessibilityValue).toEqual({+ text: "Apple unavailable",+ });++ await act(async () => {+ await retryAppleButton?.props.onPress();+ });++ expect(authFns.signInWithApple).toHaveBeenCalledTimes(2);+ expect(getTextNodes(renderer.toJSON())).not.toContain("Apple unavailable");+ });+it("marks a failed SSO sign-in on the organization step", async () => {authFns.signInWithSso.mockRejectedValueOnce(new Error("SSO unavailable"));const renderer = await renderPanel();@@ -934,6 +1026,7 @@ describe("SignInPanel", () => {shadowOpacity: 0.12,}),).toBe(false);+ expect(text).not.toContain("Sign in with Apple");expect(text).not.toContain("Login with Google");});