1

I am trying to write tests for my react native application for the first time. I have a component LoginForm that calls a hook useLoginForm inside of it, which is written like so:

//LoginForm.js

import { useLoginForm } from './hooks';
//more imports ...

export default function LoginForm() {
  //other variables ... 
  const {
    //more functions and state variables...
    isLoading,
    login
  } = useLoginForm()

  return (
    //more code...
            <TouchableOpacity
                onPress={login}
            >
                {isLoading ?
                    <ActivityIndicator accessibilityHint={"login-loading"}/>
                    :
                    <Text>
                        confirm
                    </Text>
                }
            </TouchableOpacity>

  )
}

The idea is that when I press the confirm button it replaces the text by an ActivityIndicator and it stops loading inside the login function, either because it was successful or an error occurred.

Inside the hook:

//useLoginForm.js

import { signInRequest } from "../api"
//... 

export const useLoginForm = () => {
  const [isLoading, updateIsLoading] = React.useState(false)
  // ...
  

  const login = async () => {
        updateIsLoading(true)
        await signInRequest(email, password)
          .then(data => {
            // do something ...
                updateIsLoading(false)
            }
          })
          .catch(error => {
            updateIsLoading(false)
            // ...
          })
    }
}

Also, my files are currently structured like this

─src
    └───components
        └───LoginForm
            ├───hooks
            │   ├───useLoginForm.js
            │   └───index.js
            ├───LoginForm.js
            ├───LoginForm.test.js
            └───index.js

Where index.js contains the following line:

// hooks/index.js

export { useLoginForm } from "./useLoginForm";

I am using jest and @testing-library/react-native.

I can include the test if neccessary, but at the moment it only includes some very basic assertions and events like changing input fields and pressing the confirm button

There are some things I am having trouble in understanding:

  1. How can I access the login function to check if it was called?
fireEvent.press(getByText("confirm"))
await waitForElementToBeRemoved(() => getByAccessibilityHint("login-loading"))
// the following line is what I am trying to accomplish
expect(login).toHaveBeenCalled()
  1. If I were to mock ONLY this login function with this file structure, how should I do it? I've tried several things I found across StackOverflow and had no success with neither of them.

  2. Am I exporting and importing correctly with this file structure? (I recently refactored my application, so I am still a bit unsure about this file structure)

0 Answers0