Jest Mock with Typescript, not picking up __mocks__

Viewed 420

I am having trouble getting jest to use my mocks when running tests. The only way I've gotten it to work has been to implicitly pass the Mock into the test, which isn't always possible.

My app ./App.ts is laid out pretty simply as

import { GoogleAuth } from './src/data/firebase/auth';

class App extends React.Component<{}, { initFirebase: boolean, currentUser: FirebaseAuthTypes.User | null }> {
  googleAuth: GoogleAuth;
  constructor(props) {
    super(props);
    this.state = { initFirebase: false, currentUser: null };
    this.googleAuth = new GoogleAuth({ auth });
// removed a bunch of stuff...
  render() {
    return <View style={styles.container}>
      <View style={styles.center}>
        <Text>Hello React Native Web with reload!</Text>
        <Text>{this.state.currentUser ? this.state.currentUser.displayName : null}</Text>
        <SignInGoogle
          currentUser={this.state.currentUser}
          firebaseInitialized={this.state.initFirebase}
          auth={auth}
          googleAuth={this.googleAuth}
        />
      </View>
    </View>
  }
};

When I run my test, I need to mock out ./src/data/firebase/auth so I created a replacement class in my root ./__mocks__/auth.ts, where I've reimplemented a simple version of the class with no dependencies.

import { ReactNativeFirebase } from "@react-native-firebase/app";
import { FirebaseAuthTypes } from "@react-native-firebase/auth";

export class GoogleAuth {
  public initialized: boolean;
  private auth: ReactNativeFirebase.FirebaseModuleWithStaticsAndApp<FirebaseAuthTypes.Module, FirebaseAuthTypes.Statics>;
  constructor(props: { auth: ReactNativeFirebase.FirebaseModuleWithStaticsAndApp<FirebaseAuthTypes.Module, FirebaseAuthTypes.Statics> }) {
    this.initialized = false;
    this.config();
  }


  async signIn() {
    try {
      return 'signin'
    } catch (e) {
      console.log('signin error', e);
    }
  }

  async signOut() {
    try {
      return 'signout'
    } catch (e) {
      console.log('signout error', e);
    }
  }

  private async config() {
    try {
      this.initialized = false;
    } catch (e) {
      console.log('error configuring google', e);
    }
  }
}

My understanding is that jest should look in the Mocks folder for this mock, but it doesn't pick it up. I've also placed the same file in the ./src/data/firebase/__mocks__/auth.ts and ./__mocks/src/data/firebase/auth.ts locations to see if jest can find that file, but no joy.

I've also tried mocking within my ./__tests__/App.tsx file using

import { GoogleAuth } from '../src/data/firebase/auth';
jest.mock('../src/data/firebase/auth');
// jest.fn().mockImplementation(() => {
//   return {
//     GoogleAuth: jest.mock('../src/data/firebase/auth')
//   }
// });

All with the same result the the class is not being mocked and because it is running functions that are not available in testing I'm getting errors.

0 Answers
Related