aelbore / esbuild-jest

A Jest transformer using esbuild
519 stars 51 forks source link

Presence of `jest.mock()` in React Project (even as a comment!) Causes Testing Environment to Break #54

Open jjorissen52 opened 3 years ago

jjorissen52 commented 3 years ago

This repository demonstrates the inclusion of jest.mock() (even in a comment) when using @testing-library/react in conjunction with esbuild-jest causes the test environment to break.

Reproduction

git clone git@github.com:jjorissen52/mock-breaks-tests.git
cd mock-breaks-tests
npm install
npm run test
With // jest.mock() Without //jest.mock()
Show Failure Show Success

Remedy

Use babel instead. For a demonstration:

git clone git@github.com:jjorissen52/mock-breaks-tests.git
cd mock-breaks-tests
git checkout no-longer-broken
npm install
npm run test
jjorissen52 commented 3 years ago

In case this information is helpful to someone else, I will add the shown error as text to make this page show up in search: ReferenceError: React is not defined.

akshayr20 commented 3 years ago

Try adding import React from 'react'; in your test file

jjorissen52 commented 3 years ago

@akshayr20 React is imported in the first line of both tests. To be clear, the strange bit is that the tests work as long as jest.mock() is not present anywhere in the test file. The presence of jest.mock() breaks the tests even if it's present only in the form of a comment.

akshayr20 commented 2 years ago

This might help https://github.com/evanw/esbuild/issues/412

ernie commented 2 years ago

Just got bitten by this today, and couldn't figure out why it persisted even with the mock commented out. This issue was a life(and sanity)saver. There is a workaround from #61 above, changing:

import React from "react"

to

import * as React from "react"

in the affected test files, which does indeed resolve the issue. For now, I'm just going to avoid using mocks in my little project, though.

dominik-zeglen commented 2 years ago

🤦‍♂️ I spent almost an hour just to learn i can't use new Dock() because it contains ock(.

lukeupup commented 1 year ago

🤦‍♂️ I spent almost an hour just to learn i can't use new Dock() because it contains ock(.

I've met exactly the same problem. My code contains a function named "block" and jest will report that React is not defined when I call this function like block(). And I found the problem could happen whenever there's ock( in the code, even in comment.