I've been searching for solutions related to this issue without any luck.
My goal is to write unit tests using '@testing-library/react-native' to test the functionality of calling useAuth0().authorize when the login button is pressed. I am expecting it to be called once, however, I am getting back 0 calls.
What could be the mistake in my approach?
Below is the structure of the landing page located in ./app/(login)/index.tsx:
import { StyleSheet, TouchableOpacity, SafeAreaView } from 'react-native';
import { useAuth0 } from 'react-native-auth0';
export default function Landing(): React.JSX.Element {
const { authorize, clearSession, user } = useAuth0();
const onLogin = async () => {
try {
await authorize();
} catch (e) {
console.log(e);
}
};
const loggedIn = user !== undefined && user !== null;
const onLogout = async () => {
try {
await clearSession();
} catch (e) {
console.log('Log out cancelled');
}
};
return (
<SafeAreaView style={styles.container}>
<TouchableOpacity style={styles.logBtn} onPress={loggedIn ? onLogout : onLogin} testID='loginBtn'>
{user && <Text style={styles.btnTxt}>Log Out</Text>}
{!user && <Text style={styles.btnTxt}>Log In</Text>}
</TouchableOpacity>
</SafeAreaView>
}
Here is where I am with the testing process:
import { render, fireEvent, waitFor } from '@testing-library/react-native';
import { useAuth0 } from 'react-native-auth0';
import Landing from '@/app/(login)/index';
jest.mock('react-native-auth0', () => ({
useAuth0: jest.fn(() => ({
authorize: jest.fn(),
})),
}));
describe('Ensuring that the Login page correctly interacts with Auth0 functionality', () => {
test('Verifying if the authorize function is being called upon clicking the Login button', async () => {
const { getByTestId } = render(<Landing />);
const loginBtn = getByTestId('loginBtn');
fireEvent.press(loginBtn)
await waitFor(() => {
expect(useAuth0().authorize).toHaveBeenCalledTimes(1);
})
})
})
Upon execution of the test, the following error is encountered:
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
43 | fireEvent.press(loginBtn)
44 |
> 45 | await waitFor(() => {
| ^
46 | expect(useAuth0().authorize).toHaveBeenCalledTimes(1);
47 | })
48 | })
I also attempted the following:
Changing:
fireEvent.press(loginBtn);
to
fireEvent(loginBtn, 'click');
and changing:
<TouchableOpacity></TouchableOpacity>
to
<Button></Button>
Unfortunately, neither of these strategies produced the desired outcome :(