Skip to content

unmount timing leads to "test was not wrapped in act" #999

@artola

Description

@artola
  • @testing-library/react version: 12.1.2 (but even found in v11)
  • Testing Framework and version: jest 27 (but even found in v26)
  • DOM Environment: 16.7.0

Relevant code or config:

import React, {useEffect, useRef, useState} from 'react';

import {render} from '@testing-library/react';

const MyComponent = () => {
  const [, setValue] = useState(0);
  const mountedRef = useRef(true);

  useEffect(() => {
    Promise.resolve().then(() => {
      if (mountedRef.current) {
        setValue(1);
      }
    });

    return () => {
      mountedRef.current = false;
    };
  }, []);

  return null;
};

describe('bug', () => {
  it('should not update state after unmounted', () => {
    render(<MyComponent />);
  });
});

What you did:

Run the test and see the console warning.

What happened:

console.error
    Warning: An update to MyComponent inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */
    
    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act

Problem description:

The test run, but a warning is printed in the console. If we use the unmount inside the it, then there is no such warning.
Running the unmount inside the test should not be needed as it runs in the afterEach => cleanup => unmount (see api doc).

See the cleanup is added to afterEach on jest and triggered, but seems "later" that if call it inside the same test.

no warning:

  it('should not update state after unmounted', () => {
    render(<MyComponent />);

    cleanup();
  });

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