You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Detox测试react-native-auth0库?求Mock请求实现方案

在React Native中Mock Auth0的webAuth.authorize方法(用于Detox测试)

步骤1:封装Auth0服务(推荐)

避免在组件中直接调用auth0.webAuth.authorize,先封装成独立的服务模块,方便后续Mock:

// src/services/authService.js
import auth0 from 'react-native-auth0';

const auth0Instance = new auth0({
  domain: '你的Auth0域名',
  clientId: '你的Auth0客户端ID',
});

export const loginWithAuth0 = () => {
  return auth0Instance.webAuth.authorize({
    scope: 'openid profile email',
    audience: 'https://你的API受众',
  });
};

组件中调用这个封装方法:

// src/components/LoginButton.js
import { loginWithAuth0 } from '../services/authService';

const LoginButton = () => {
  const handleLogin = async () => {
    try {
      const authResult = await loginWithAuth0();
      // 处理登录成功逻辑,比如存储token、跳转首页
    } catch (error) {
      // 处理错误
    }
  };

  return <Button title="登录" onPress={handleLogin} />;
};

步骤2:在Detox测试中Mock封装的服务

使用Jest的jest.mock方法替换loginWithAuth0的实现,模拟成功或失败的返回值:

// e2e/login.test.js
import * as authService from '../src/services/authService';

// Mock auth服务,返回模拟的登录结果
jest.mock('../src/services/authService', () => ({
  loginWithAuth0: jest.fn().mockResolvedValue({
    accessToken: 'mock-access-token-123',
    idToken: 'mock-id-token-456',
    user: { name: '测试用户', email: 'test@example.com' },
  }),
}));

describe('登录流程', () => {
  it('点击登录按钮后完成Mock登录并跳转首页', async () => {
    // 启动App后,找到登录按钮并点击
    await element(by.id('login-button')).tap();

    // 验证登录方法被调用
    expect(authService.loginWithAuth0).toHaveBeenCalled();

    // 验证成功跳转到首页
    await expect(element(by.id('home-screen'))).toBeVisible();
  });

  it('模拟登录失败场景', async () => {
    // 重写Mock,返回失败结果
    authService.loginWithAuth0.mockRejectedValue(new Error('登录失败'));

    await element(by.id('login-button')).tap();

    // 验证错误提示是否显示
    await expect(element(by.text('登录失败'))).toBeVisible();
  });
});

步骤3:如果未封装,直接Mock react-native-auth0模块

如果项目中直接使用auth0实例,可直接Mock整个react-native-auth0库:

// e2e/login.test.js
jest.mock('react-native-auth0', () => {
  // Mock Auth0构造函数
  return jest.fn().mockImplementation(() => ({
    webAuth: {
      // Mock authorize方法
      authorize: jest.fn().mockResolvedValue({
        accessToken: 'mock-token',
        user: { name: '测试用户' },
      }),
    },
  }));
});

这样点击按钮后,实际的Auth0授权流程不会触发,而是直接使用Mock的返回值,配合Detox完成UI交互测试。

内容的提问来源于stack exchange,提问作者Lavínia Beghini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:37:40