Skip to content

Testing library environment does not call ref.current.focus() #1069

@24dlong

Description

@24dlong

Describe the bug

A component in my app focuses a TextInput after a parent Pressable receives a press. I'm using a ref to identify and focus the TextInput element. My desired functionality works just fine when running my app through expo, but my test is failing because it seems that the onFocus event is not being called.

Expected behavior

When Pressable is pressed via fireEvent, I would expect inputElement.current.focus() to successfully run, triggering the onFocus mock event.

Steps to Reproduce

Here's some example code:

Foo.js

import {Pressable, TextInput} from "react-native";
import {useRef} from "react";

const Foo = (props) => {
    const inputRef = useRef()

    return (
        <Pressable testID={"pressable"} onPress={() => inputRef.current.focus()}>
            <TextInput ref={inputRef} testID={"input"} onFocus={props.onFocus} />
        </Pressable>
    )
}

export default Foo;

Foo.test.js

import { render, screen, fireEvent } from '@testing-library/react-native';
import Foo from "./foo";

test('onFocus is called after press', () => {
    const mockFocus = jest.fn();
    render(<Foo onFocus={mockFocus} />)
    fireEvent.press(screen.getByTestId("pressable"));
    expect(mockFocus).toHaveBeenCalled()
});

When I run npm test, this test fails with the following message:

Error: expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

Versions

npmPackages:
   @testing-library/react-native: ^11.0.0 => 11.0.0 
   react: ^17.0.2 => 17.0.2 
   react-native: ^0.68.3 => 0.68.3 
   react-test-renderer: ^17.0.2 => 17.0.2 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions