Passing top-level mock function into jest.mock implementation

Viewed 226

I would like to test that a function being returned from a mocked function is called in a test in jest.

I have the following mock:


const mockPromptAsync = jest.fn();

jest.mock("expo-auth-session/providers/facebook", () => ({
  useAuthRequest: jest
    .fn()
    .mockReturnValue([
      { foo: true },
      { type: "success", params: { access_token: "123" } },
      mockPromptAsync,
    ]),
}));

Where in my component I have:

  const [request, response, promptAsync] = Facebook.useAuthRequest({
    responseType: ResponseType.Token,
    clientId: Constants.manifest.extra.FACEBOOK_CLIENT_ID,
  });

I want to test that the onPress here calls mockPromptAsync:

      <Button
        title="Login with Facebook"
        disabled={!request}
        onPress={() => {
          promptAsync();
        }}
      />

However, it seems like mockPromptAsync is undefined during the test:

expect(mockPromptAsync).toBeCalledTimes(1);

promptAsync is also undefined when I console.log in my component.

1 Answers

So the solution I went with was to define jest.fn() inline still, and perform the expect call be instantiating the mock:

import { useAuthRequest} from "expo-auth-session/providers/facebook";

...

expect(useAuthRequest()[2]).toBeCalledTimes(1)
Related