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

TypeScript环境下Jest无法识别__mocks__文件的问题求助

Fixing Jest Mock Not Working for GoogleAuth Class in React Native

Let's walk through how to get your GoogleAuth mock working properly in Jest—no more relying on explicit mock object passing. Here's what you need to adjust:

1. Verify the mocks Directory Structure

Jest looks for mocks based on the exact relative path of your original module. Since your GoogleAuth lives at src/data/firebase/auth.ts, your mock file must be placed at:

src/data/firebase/__mocks__/auth.ts

This is the only path Jest will automatically associate with your original module when using relative imports. The root-level __mocks__ or misaligned paths you tried won't work for relative module imports.

Your existing mock class in this location is fine—keep that simplified GoogleAuth implementation.

2. Correctly Configure the Mock in Your Test File

In __tests__/App.tsx, update your mock setup to properly mock the class and control its behavior:

import { render } from '@testing-library/react-native';
import App from '../App';
import { GoogleAuth } from '../src/data/firebase/auth';

// Tell Jest to use our mock file for the auth module
jest.mock('../src/data/firebase/auth');

// Type assertion to access mock-specific methods (avoids TypeScript errors)
const MockedGoogleAuth = GoogleAuth as jest.Mock<GoogleAuth>;

describe('App Component', () => {
  beforeEach(() => {
    // Reset the mock between tests to avoid cross-test contamination
    MockedGoogleAuth.mockClear();

    // Customize the mock instance behavior (optional but useful)
    MockedGoogleAuth.mockImplementation(() => ({
      initialized: true,
      signIn: jest.fn().mockResolvedValue('signin'),
      signOut: jest.fn().mockResolvedValue('signout'),
    }));
  });

  it('initializes GoogleAuth on mount', () => {
    render(<App />);
    
    // Verify the mock class was instantiated once
    expect(MockedGoogleAuth).toHaveBeenCalledTimes(1);
    // Verify it received the expected auth prop
    expect(MockedGoogleAuth).toHaveBeenCalledWith(expect.objectContaining({ auth: expect.any(Object) }));
  });

  it('uses mock signIn method when triggered', async () => {
    const { getByText } = render(<App />);
    // Trigger your sign-in action (adjust based on your SignInGoogle component)
    await getByText('Sign In with Google').props.onPress();

    // Verify the mock signIn method was called
    const appInstance = App.prototype;
    expect(appInstance.googleAuth.signIn).toHaveBeenCalled();
  });
});

3. Check for Jest Configuration Issues

If the mock still isn't working, double-check your jest.config.js (or package.json jest field) for these common pitfalls:

  • Ensure automock: true (this is the default, but if you set it to false, Jest won't auto-detect mocks directories)
  • Remove any moduleNameMapper entries that might be overriding the path to your auth module
  • Confirm roots includes your src directory so Jest can resolve modules correctly

4. Fallback: Inline Mock (If Directory Mock Fails)

If you still can't get the directory-based mock to work, use an inline mock directly in your test file:

jest.mock('../src/data/firebase/auth', () => ({
  GoogleAuth: jest.fn().mockImplementation(() => ({
    initialized: false,
    signIn: jest.fn().mockResolvedValue('signin'),
    signOut: jest.fn().mockResolvedValue('signout'),
  })),
}));

This bypasses the mocks directory entirely and gives you direct control over the mock behavior.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:53:39