My goal is to create a mock for the firebase.auth object in react-native-firebase
, specifically targeting the signInWithCredential method. This mock will allow me to test my code effectively.
The code I am testing looks like this:
public async FacebookSignIn(): Promise<void> {
try {
const result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']);
if (result.isCancelled) {
throw new Error('User cancelled request');
}
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
throw new Error('Something went wrong obtaining the users access token');
}
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
await firebase.auth().signInWithCredential(credential);
}
catch (error) {
console.error(error);
}
}
To ensure that my function calls signInWithCredential correctly, I have set up a test case using a global mock function named func
:
describe('FacebookSignIn', () => {
it('should sign in user with facebook credentials', async () => {
await service.FacebookSignIn();
expect(func).toHaveBeenCalled();
})
})
However, when trying to use the following mock, I encounter the error
TypeError: Cannot read property 'credential' of undefined
:
jest.mock('react-native-firebase', () => {
return {
auth: () => {
return {
currentUser: null,
signOut: func,
signInAnonymously: func,
signInWithEmailAndPassword: func,
signInWithCredential: func,
FacebookAuthProvider: jest.fn(() => {
return {
credential: jest.fn(() => {
return {
provider: 'dummy',
token: '1234',
secret: '5678'
}
})
}
})
}
}
}
});
I've examined the type definition for firebase.auth
which includes AuthStatics, but still encountering issues with mocking FacebookAuthProvider. The AuthStatics interface defines various other methods related to authentication providers.
How can I successfully mock the FacebookAuthProvider property and resolve the issue of it being undefined for the credential?