Skip to content

Unexpected failing test when mixing promises and useEffect #1093

Closed
@AugustinLF

Description

@AugustinLF

Describe the bug

I've written a small test case demonstrating issues I've had when combining user event (press) -> promise -> setState -> useEffect. The test case fails for RNTL but passes on @testing-library/react.

test.only('async event with fireEvent', async () => {
  const Comp = ({ onPress }: { onPress: () => void }) => {
    const [state, setState] = React.useState(false);

    React.useEffect(() => {
      console.log('useEffect');
      if (state) {
        console.log('onPress');
        onPress();
      }
    }, [state, onPress]);

    return (
      <Pressable
        onPress={async () => {
          console.log('waiting');
          await Promise.resolve();
          console.log('setting');
          setState(true);
        }}
      >
        <Text>Trigger</Text>
      </Pressable>
    );
  };

  const spy = jest.fn();
  const { getByText } = render(<Comp onPress={spy} />);

  fireEvent.press(getByText('Trigger'));

  await waitFor(() => {
    console.log('checking');
    expect(spy).toHaveBeenCalled();
  });
});

Logs go:

useEffect
waiting
checking
setting
checking
... a bunch of other `checking`
checking
useEffect
onPress

Note that the final onPress call (the one that we're waiting for) happens after the last check.

Expected behavior

It works as expected on web, with those logs

useEffect
waiting
checking
setting
useEffect
onPress
checking

I'll do more investigation to figure out what's happening, but if anyone manage to fix it, feel free to do so :) I kind of expect this issue to be related to a lot of the ones we've had around problems with waitFor, or async act ....

Versions

Latest main, commit of cb46ae2689cc661879e8609766041bf93f1d3137.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions