Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-test-renderer with jest.resetModules: invariant violiation for hooks #16012

Closed
entropitor opened this issue Jun 27, 2019 · 4 comments
Closed

Comments

@entropitor
Copy link

Do you want to request a feature or report a bug?
bug

What is the current behavior?
When writing a test with jest (and requiring a component with hooks after jest.resetModules()), react-test-renderer complains

Invariant Violation: Hooks can only be called inside the body of a function component. (https://fb.me/react-invalid-hook-call)

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

  1. Write a functional component using a hook
  2. Create a test using jest
  3. Call jest.resetModules
  4. Require the module
  5. Call renderer.create(<MyComponent />).toJSON()
  6. Run test, it fails with the error above

What is the expected behavior?
The test should not crash on hooks in tests where resetModules() is called

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
16.8. as hooks were introduced

@threepointone
Copy link
Contributor

Please share a repro on codesandbox or as a git repo.

@entropitor
Copy link
Author

@threepointone I've set up an example at https://github.com/entropitor/react-issue-16012

The first test case succeeds, showing that the repo is set up correctly, but the second one, using resetModules is failing (which it shouldn't)

@threepointone
Copy link
Contributor

I made a PR to your repo that fixes it. entropitor/react-issue-16012#1 more of a jest issue; you should refresh modules after resetting it.

@bmmpt
Copy link

bmmpt commented Sep 24, 2019

Maybe I'm missing something, but it seems to me the modules were already being refreshed...

Why is

const MyComponent = require("./index.js");

needed in the test if it's already in the beforeEach, after resetModules?

MyComponent = require("./index.js");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants