9

I used "useEffect" to achieve functionality of "componentWillUnmount" in functional component. How to trigger that while testing the component using Jest/Enzyme?

My Component:

const myComp = () => {
  useEffect(() => () => {
    console.log('Unmounted');
  }, []);
  return <div>Test</div>;
}
1
  • @slideshowp2, thanks for your reply. You may not noticed I put console.log in return function, not in the callback. Or can you show me the right way...? Commented May 7, 2021 at 15:34

2 Answers 2

19

If you are using react-testing-library then:

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

Sign up to request clarification or add additional context in comments.

Comments

4

According to this issue, we know that shallow render doesn't support the useEffect hook. We need to use mount and call .unmount() method manually.

E.g.

index.tsx:

import React, { useEffect } from 'react';

export const MyComp = () => {
  useEffect(
    () => () => {
      console.log('Unmounted');
    },
    []
  );
  return <div>Test</div>;
};

index.test.tsx:

import React from 'react';
import { mount } from 'enzyme';
import { MyComp } from './';

describe('67384129', () => {
  it('should pass', () => {
    const wrapper = mount(<MyComp />);
    wrapper.unmount();
  });
});

test result:

 PASS  examples/67384129/index.test.tsx (8.233 s)
  67384129
    ✓ should pass (53 ms)

  console.log
    Unmounted

      at examples/67384129/index.tsx:6:15

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.121 s

package versions:

"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0"
"jest": "^26.6.3",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",

1 Comment

This is what I was looking for. wrapper.unmount. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.