react-testing-library: Incorrect behavior after set injectGlobals: false in jest config

"@testing-library/react": "^14.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",

Relevant code or config:

I’m trying to switch from injected globals to import needed functions from @jest/globals

i just add insectGlobals: false in jest.config.ts

What you did:

I added needed imports to test file and tests fails with errors like:

expect(received).toHaveLength(expected)

    Expected length: 0
    Received length: 1

What happened:

errors are reproduced only if there are two or more tests

it looks like the render result is not reset and they are rendered into one document

Reproduction:

Here an repo with example of incorrect behavior

https://github.com/krutoo/testing-library-react-jest-no-inject-globals

About this issue

  • Original URL
  • State: closed
  • Created 9 months ago
  • Comments: 15 (6 by maintainers)

Most upvoted comments

@krutoo I’ve created a PR to add a warning in that case.

@leonadler AFAIR, IS_REACT_ACT_ENVIRONMENT wasn’t available before React 18, what React did before was testing if typeof jest === 'undefined' so this code is 100% relevant for React >=18. If consumers use setGlobals: false`, they should do this on their own. I’m hesitating if we should write this in the docs too.

Hi @krutoo, thanks for opening this. As written in the docs for cleanup:

Please note that this is done automatically if the testing framework you’re using supports the afterEach global and it is injected to your testing environment (like mocha, Jest, and Jasmine). If not, you will need to do manual cleanups after each test.

Since there’s no afterEach, no cleanup is being called. If you believe this phrasing isn’t clear enough, we’re open for PR’s in our docs repo.

I’m closing this one because as already written here by @leonadler, we can’t have dedicated code for each test runner nor we wan’t to inject an afterEach if it’s not injected because that’s too invasive.