Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

13.8 KB
Raw Blame
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { useSignUp } from './useSignUp';

const mockNavigate = vi.hoisted(() => vi.fn());
const mockSearchParamsGet = vi.hoisted(() => vi.fn().mockReturnValue(null));
const mockMessageError = vi.hoisted(() => vi.fn());
const mockSignUpEmail = vi.hoisted(() => vi.fn());
const mockGetCaptchaTokenOnError = vi.hoisted(() => vi.fn());
const mockPreSocialSignupCheck = vi.hoisted(() => vi.fn(async () => true));
const mockTranslate = vi.hoisted(() => vi.fn());

vi.mock('react-router', () => ({
  useNavigate: () => mockNavigate,
  useSearchParams: () => [{ get: mockSearchParamsGet }],
}));

vi.mock('@lobehub/ui', async (importOriginal) => ({
  ...(await importOriginal<object>()),
  toast: { error: mockMessageError, success: vi.fn() },
}));

vi.mock('@/libs/better-auth/auth-client', () => ({
  signUp: { email: mockSignUpEmail },
}));

vi.mock('@lobechat/business-const', () => ({
  BRANDING_NAME: 'LobeHub',
  ORG_NAME: 'LobeHub',
}));

vi.mock('@/business/client/hooks/useBusinessSignup', () => ({
  useBusinessSignup: () => ({
    businessElement: null,
    getCaptchaTokenOnError: mockGetCaptchaTokenOnError,
    getFetchOptions: async () => undefined,
    preSocialSignupCheck: mockPreSocialSignupCheck,
  }),
}));

vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: mockTranslate,
  }),
}));

let mockEnableEmailVerification = false;
let mockEnableBusinessFeatures = false;
vi.mock('@/features/AuthShell/AuthServerConfigProvider', () => ({
  useAuthServerConfigStore: (selector: (s: any) => any) =>
    selector({
      serverConfig: {
        enableBusinessFeatures: mockEnableBusinessFeatures,
        enableEmailVerification: mockEnableEmailVerification,
      },
    }),
}));

const originalLocation = window.location;

describe('useSignUp', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockSearchParamsGet.mockReturnValue(null);
    mockGetCaptchaTokenOnError.mockResolvedValue(undefined);
    mockPreSocialSignupCheck.mockResolvedValue(true);
    mockTranslate.mockImplementation((key: string, options?: Record<string, unknown>) => {
      if (key === 'authError:codes.DELETED_ACCOUNT_EMAIL_WITH_RETRY_AFTER_DAYS') {
        return `Retry within ${options?.count} days`;
      }
      if (key === 'authError:codes.DELETED_ACCOUNT_EMAIL') return 'Static cooldown';

      return typeof options?.defaultValue === 'string' ? options.defaultValue : key;
    });
    mockEnableBusinessFeatures = false;
    mockEnableEmailVerification = false;
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: { ...originalLocation, href: '', origin: originalLocation.origin },
      writable: true,
    });
  });

  afterEach(() => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: originalLocation,
      writable: true,
    });
    vi.restoreAllMocks();
  });

  describe('initial state', () => {
    it('should return initial values', () => {
      const { result } = renderHook(() => useSignUp());

      expect(result.current.loading).toBe(false);
      expect(result.current.onSubmit).toBeInstanceOf(Function);
    });
  });

  describe('handleSignUp', () => {
    const validValues = {
      confirmPassword: 'Password123!',
      email: '[email protected]',
      password: 'Password123!',
    };

    it('should call signUp.email with correct params', async () => {
      mockSignUpEmail.mockResolvedValue({ error: null });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(mockSignUpEmail).toHaveBeenCalledWith(
        expect.objectContaining({
          email: '[email protected]',
          name: 'new',
          password: 'Password123!',
        }),
      );
    });

    it('should stop sign up when business pre-check rejects', async () => {
      mockEnableBusinessFeatures = true;
      mockPreSocialSignupCheck.mockResolvedValue(false);

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(mockPreSocialSignupCheck).toHaveBeenCalledWith(validValues);
      expect(mockSignUpEmail).not.toHaveBeenCalled();
    });

    it('should redirect to onboarding on success', async () => {
      mockSignUpEmail.mockResolvedValue({ error: null });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(window.location.href).toBe('/onboarding');
    });

    it('should thread callbackUrl from search params through onboarding', async () => {
      mockSearchParamsGet.mockImplementation((key: string) =>
        key === 'callbackUrl' ? '/dashboard' : null,
      );
      mockSignUpEmail.mockResolvedValue({ error: null });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(mockSignUpEmail).toHaveBeenCalledWith(
        expect.objectContaining({
          callbackURL: `${originalLocation.origin}/onboarding?callbackUrl=%2Fdashboard`,
        }),
      );
      expect(window.location.href).toBe('/onboarding?callbackUrl=%2Fdashboard');
    });

    it('should redirect to verify-email when email verification is enabled', async () => {
      mockEnableEmailVerification = true;
      mockSignUpEmail.mockResolvedValue({ error: null });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(mockNavigate).toHaveBeenCalledWith(
        expect.stringContaining('/verify-email?email=new%40example.com'),
      );
    });

    it('should derive username from email prefix', async () => {
      mockSignUpEmail.mockResolvedValue({ error: null });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit({ ...validValues, email: '[email protected]' });
      });

      expect(mockSignUpEmail).toHaveBeenCalledWith(expect.objectContaining({ name: 'john.doe' }));
    });

    it('should show error for duplicate email', async () => {
      mockSignUpEmail.mockResolvedValue({
        error: {
          code: 'FAILED_TO_CREATE_USER',
          details: { cause: { code: '23505' } },
        },
      });

      const { result } = renderHook(() => useSignUp());
      const setErrors = vi.spyOn(result.current.form, 'setErrors');

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(setErrors).toHaveBeenCalledWith({ email: 'betterAuth.errors.emailRegistered' });
      expect(mockMessageError).not.toHaveBeenCalled();
      expect(mockNavigate).not.toHaveBeenCalled();
      expect(window.location.href).toBe('');
    });

    it('should show error for invalid email', async () => {
      mockSignUpEmail.mockResolvedValue({
        error: { code: 'INVALID_EMAIL', message: 'Invalid email' },
      });

      const { result } = renderHook(() => useSignUp());
      const setErrors = vi.spyOn(result.current.form, 'setErrors');

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(setErrors).toHaveBeenCalledWith({ email: 'betterAuth.errors.signupEmailInvalid' });
      expect(mockMessageError).not.toHaveBeenCalled();
      expect(mockNavigate).not.toHaveBeenCalled();
      expect(window.location.href).toBe('');
    });

    it('should show actionable copy next to submit for unknown codes, never the raw message', async () => {
      vi.spyOn(console, 'error').mockImplementation(() => {});
      mockSignUpEmail.mockResolvedValue({
        error: { code: 'SOME_UNKNOWN_CODE', message: 'SOME_UNKNOWN_CODE' },
      });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(result.current.formError).toBe('betterAuth.signup.failed');
      expect(mockMessageError).not.toHaveBeenCalled();
      expect(mockNavigate).not.toHaveBeenCalled();
      expect(window.location.href).toBe('');
    });

    it('should show a translated non-field error next to the submit button', async () => {
      mockTranslate.mockImplementation((key: string, options?: Record<string, unknown>) => {
        if (key === 'authError:codes.SIGNUP_IP_BURST') return 'Too many sign-ups, wait a while';
        return typeof options?.defaultValue === 'string' ? options.defaultValue : key;
      });
      mockSignUpEmail.mockResolvedValue({
        error: { code: 'SIGNUP_IP_BURST', message: 'Please try again later.' },
      });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(result.current.formError).toBe('Too many sign-ups, wait a while');
      expect(mockMessageError).not.toHaveBeenCalled();
    });

    it('should show the rounded remaining cooldown in days under the email field', async () => {
      mockSignUpEmail.mockResolvedValue({
        error: {
          code: 'DELETED_ACCOUNT_EMAIL',
          message: 'DELETED_ACCOUNT_EMAIL',
          retryAfterDays: 4,
        },
      });

      const { result } = renderHook(() => useSignUp());
      const setErrors = vi.spyOn(result.current.form, 'setErrors');

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(setErrors).toHaveBeenCalledWith({ email: 'Retry within 4 days' });
      expect(mockMessageError).not.toHaveBeenCalled();
    });

    it.each([0, -1, 1.5, '4', Number.POSITIVE_INFINITY])(
      'should ignore an invalid retry-after day value: %s',
      async (retryAfterDays) => {
        mockSignUpEmail.mockResolvedValue({
          error: {
            code: 'DELETED_ACCOUNT_EMAIL',
            message: 'DELETED_ACCOUNT_EMAIL',
            retryAfterDays,
          },
        });

        const { result } = renderHook(() => useSignUp());
        const setErrors = vi.spyOn(result.current.form, 'setErrors');

        await act(async () => {
          await result.current.onSubmit(validValues);
        });

        expect(setErrors).toHaveBeenCalledWith({ email: 'Static cooldown' });
      },
    );

    it('should fall back to the static error copy when the dynamic key is unavailable', async () => {
      mockTranslate.mockImplementation((key: string, options?: Record<string, unknown>) => {
        if (key === 'authError:codes.DELETED_ACCOUNT_EMAIL') return 'Static cooldown';
        return typeof options?.defaultValue === 'string' ? options.defaultValue : key;
      });
      mockSignUpEmail.mockResolvedValue({
        error: {
          code: 'DELETED_ACCOUNT_EMAIL',
          message: 'DELETED_ACCOUNT_EMAIL',
          retryAfterDays: 4,
        },
      });

      const { result } = renderHook(() => useSignUp());
      const setErrors = vi.spyOn(result.current.form, 'setErrors');

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(setErrors).toHaveBeenCalledWith({ email: 'Static cooldown' });
    });

    it('should retry sign up with captcha token when captcha is required', async () => {
      mockGetCaptchaTokenOnError.mockResolvedValue('captcha-token');
      mockSignUpEmail
        .mockResolvedValueOnce({
          error: { code: 'CAPTCHA_REQUIRED', message: 'Missing CAPTCHA response' },
        })
        .mockResolvedValueOnce({ error: null });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(mockSignUpEmail).toHaveBeenCalledTimes(2);
      expect(mockSignUpEmail).toHaveBeenLastCalledWith(
        expect.objectContaining({
          fetchOptions: { headers: { 'x-captcha-response': 'captcha-token' } },
        }),
      );
      expect(mockMessageError).not.toHaveBeenCalled();
      expect(window.location.href).toBe('/onboarding');
    });

    it('should stop sign up when captcha modal is cancelled', async () => {
      mockGetCaptchaTokenOnError.mockResolvedValue(null);
      mockSignUpEmail.mockResolvedValue({
        error: { code: 'CAPTCHA_REQUIRED', message: 'Missing CAPTCHA response' },
      });

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(mockSignUpEmail).toHaveBeenCalledTimes(1);
      expect(mockMessageError).not.toHaveBeenCalled();
      expect(mockNavigate).not.toHaveBeenCalled();
      expect(window.location.href).toBe('');
    });

    it('should show a network hint next to submit on unexpected exception', async () => {
      vi.spyOn(console, 'error').mockImplementation(() => {});
      mockSignUpEmail.mockRejectedValue(new Error('network error'));

      const { result } = renderHook(() => useSignUp());

      await act(async () => {
        await result.current.onSubmit(validValues);
      });

      expect(result.current.formError).toBe('betterAuth.errors.requestFailed');
      expect(mockMessageError).not.toHaveBeenCalled();
    });

    it('should set loading during sign up and reset after', async () => {
      let resolveSignUp: (v: any) => void;
      mockSignUpEmail.mockReturnValue(
        new Promise((resolve) => {
          resolveSignUp = resolve;
        }),
      );

      const { result } = renderHook(() => useSignUp());

      let submitPromise: Promise<void>;
      act(() => {
        submitPromise = result.current.onSubmit(validValues);
      });

      expect(result.current.loading).toBe(true);

      await act(async () => {
        resolveSignUp!({ error: null });
        await submitPromise!;
      });

      expect(result.current.loading).toBe(false);
    });
  });
});