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

Facebook.useAuthRequest导致Jest测试失败,求可行解决方案

Facebook登录组件Jest测试失败问题解决办法

问题背景

我按照指南实现了一个简易Facebook登录功能,该功能在Android和Web端运行正常,但执行Jest测试时出现失败。

组件代码

import React, { useState, useEffect } from 'react';
import { Fontisto } from '@expo/vector-icons';

import * as AuthSession from 'expo-auth-session';
import * as Facebook from 'expo-auth-session/providers/facebook';
import * as WebBrowser from 'expo-web-browser';

import {
  StyledButton,
  ButtonText,
  Colors,
} from './styles.js';

// Colors
const { primary } = Colors;

WebBrowser.maybeCompleteAuthSession();

function FacebookLogin({ navigation }) {
  const [user, setUser] = useState(null);
  const [request, response, promptAsync] = Facebook.useAuthRequest({
    clientId: '1264001381219589',
  });

  useEffect(() => {
    if (response && response.type === 'success' && response.authentication) {
      (async () => {
        const userInfoResponse = await fetch(
          `https://graph.facebook.com/me?access_token=${response.authentication.accessToken}&fields=id,name,email,about,picture.type(large),link`,
        );
        const userInfo = await userInfoResponse.json();
        setUser(userInfo);
        console.log(JSON.stringify(response, null, 2));
        console.log(userInfo);
      })();
    } else {
      console.log('something is not working! ', response);
    }
  }, [response]);

  const handlePressAsync = async () => {
    const result = await promptAsync();
    if (result.type !== 'success') {
      alert('Uh oh, something went wrong');
    }
  };

  return (
    <StyledButton facebook onPress={handlePressAsync}>
      <Fontisto name="facebook" color={primary} size={25} />
      <ButtonText facebook>Sign in with Facebook </ButtonText>
    </StyledButton>
  );
}

export default FacebookLogin;

测试代码

import React from 'react';
import { render, fireEvent, waitFor } from '@testing-library/react-native';
import * as AuthSession from 'expo-auth-session';
import FacebookLogin from '../../components/FacebookLogin';

describe('FacebookLogin', () => {
  it('renders correctly', () => {
    const tree = render(<FacebookLogin />).toJSON();
    expect(tree).toMatchSnapshot();
  });
});

报错信息

expo-linking needs access to the expo-constants manifest (app.json or app.config.js) to determine what URI scheme to use. Setup the manifest and rebuild: https://github.com/expo/expo/blob/main/packages/expo-constants/README.md

已在package.json中安装expo-constants(版本~14.2.1),但问题仍未解决,以下是可行的解决办法:


解决办法

1. 模拟expo-constants模块

Jest测试环境无法读取真实的app.json配置,需手动模拟该模块:

  • 创建jest.setup.js文件,添加以下代码:
    jest.mock('expo-constants', () => ({
      manifest: {
        scheme: 'your-app-scheme' // 替换为你app.json中的scheme值
      }
    }));
    
  • 在jest.config.js中指定该setup文件:
    module.exports = {
      setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
      // 其他Jest配置项...
    };
    

2. 模拟Facebook授权相关模块

测试不需要真实的授权流程,直接模拟useAuthRequest和WebBrowser的方法:
在测试文件顶部添加以下模拟代码:

jest.mock('expo-auth-session/providers/facebook', () => ({
  useAuthRequest: jest.fn(() => [null, null, jest.fn()]),
}));
jest.mock('expo-web-browser', () => ({
  maybeCompleteAuthSession: jest.fn(),
}));

3. 确认app.json配置完整性

确保app.json中存在scheme字段,示例:

{
  "expo": {
    "scheme": "your-app-scheme",
    // 其他配置...
  }
}

4. 清除依赖缓存并重装

执行以下命令清除缓存并重新安装依赖:

npm cache clean --force
rm -rf node_modules package-lock.json
npm install

内容的提问来源于stack exchange,提问作者bralyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:55:17