testing-library / react-testing-library

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

Home Page:https://testing-library.com/react

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React Testing library `unmount` is not working

bhushanlaware opened this issue · comments

Here is my code where issue is happening. umnount seems like not doing the basic job which is to unmount react component. You see I have kept the console log in react useEfect return callback which is not being logged.

  React.useEffect(() => {
    emitter.on(MY_EVENT,callback);

    return () => { 
      console.log('unsubscribing'); // <<--- Its not getting console logged.
      emitter.off(MY_EVENT, callback);
    };
  }, []);
  it.only('should add and remove event listeners', () => {
    const { unmount } = render(<Component {...defaultProps} />);
    expect(emitter.on).toHaveBeenCalledTimes(1);
    expect(observers[MY_EVENT).toBeDefined();


    unmount();
    expect(emitter.off).toHaveBeenCalledTimes(1);
    expect(observers[MY_EVENT]).toBeUndefined();
  });
});
    expect(jest.fn()).toHaveBeenCalledTimes(expected)

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

      23 |
      24 |     unmount();
    > 25 |     expect(emitter.off).toHaveBeenCalledTimes(1);
          |                         ^
      26 |     expect(observers[MY_EVENT]).toBeUndefined();

here is my packages version

   "react": "17.0.2",
   "react-dom": "17.0.2"
   "@testing-library/jest-dom": "5.15.0",
   "@testing-library/react": "12.1.2",

Expecting to execute the React.useEffect return callback when unmount is called.

Hi @bhushanlaware,
Unfortunately, we're not maintaining RTL version 12, the current version is 14. The version you're using was released over 3 years ago.
This functionality works for the latest version as can be seen in this repro.
I recommend at least upgrading to the latest version (version 12 has updated versions).