Skip to content

Unable to test useEffect cleanup functions (RN 0.64) #705

Closed
@michaelgmcd

Description

@michaelgmcd

Describe the bug

Might be related to testing-library/react-testing-library#874. When testing useEffect cleanup functions using unmount, they are not called synchronously. Wrapping unmount() in act seems to work:

Fails

import * as React from 'react';
import { render } from '@testing-library/react-native';

describe('Testing react navigation', () => {
  test('should work', async () => {
    const fn = jest.fn();
    const Component = () => {
      React.useEffect(() => {
        return () => {
          fn();
        };
      });

      return null;
    };

    const { unmount } = render(<Component />);

    unmount();

    expect(fn).toHaveBeenCalledTimes(1);
  });
});

Passes

import * as React from 'react';
import { render } from '@testing-library/react-native';
import { act } from 'react-test-renderer';

describe('Testing react navigation', () => {
  test('should work', async () => {
    const fn = jest.fn();
    const Component = () => {
      React.useEffect(() => {
        return () => {
          fn();
        };
      });

      return null;
    };

    const { unmount } = render(<Component />);

    act(() => {
      unmount();
    });

    expect(fn).toHaveBeenCalledTimes(1);
  });
});

Expected behavior

Example test should pass (it did in RN 0.63.x). Is wrapping with act expected?

Steps to Reproduce

Example:
https://github.com/michaelgmcd/react-native-testing-library/blob/master/examples/reactnavigation/src/__tests__/AppNavigator.test.js

Versions

@testing-library/react-native: ^7.2.0 => 7.2.0
react: ^17.0.1 => 17.0.1
react-native: ^0.64.0 => 0.64.0
react-test-renderer: ^17.0.1 => 17.0.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions