vercel / next.js

The React Framework
https://nextjs.org
MIT License
124.4k stars 26.54k forks source link

Adding Vercel Analytics Breaks Jest Tests #59625

Open bmanquen opened 8 months ago

bmanquen commented 8 months ago

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/crimson-wave-5vnmml?file=%2Fapp%2Flayout.tsx%3A10%2C9-10%2C22

To Reproduce

  1. Add Vercel Analytics to any project following the docs
  2. Run currently working Jest tests
  3. Then you should get the error, "SyntaxError: Cannot use import statement outside a module" from Jest

If using the link to the sample code that reproduces the error:

  1. Run yarn test and you will see the error.
  2. Remove <Analytics /> from the layout.tsx page.
  3. Re-run yarn test and the test will pass with no errors.

Current vs. Expected behavior

I expect adding Vercel Analytics to not affect current working Jest tests. Here is the error I get when running Jest tests after adding Vercel Analytics, image

Verify canary release

Provide environment information

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Home
Binaries:
  Node: 18.18.2
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.0.5-canary.12
  eslint-config-next: 14.0.1
  react: 18.2.0
  react-dom: 18.2.0
  typescript: 5.1.6
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Jest (next/jest)

Additional context

No response

bclark8923 commented 4 months ago

Ran into this myself too

bclark8923 commented 3 months ago

I "hack" fixed this by mocking those globally in my jest tests

jest.mock("@vercel/analytics/react", () => ({
  Analytics: jest.fn() 
}))
jest.mock("@vercel/speed-insights/next", () => ({
  SpeedInsights: jest.fn() 
}))

But the issue isn't a Next problem, it's that Analytics, etc. are ES6 Packages that JEST can't parse properly. You can find various answers around for ES6 + Jest solutions

bmanquen commented 3 months ago

I "hack" fixed this by mocking those globally in my jest tests

jest.mock("@vercel/analytics/react", () => ({
  Analytics: jest.fn() 
}))
jest.mock("@vercel/speed-insights/next", () => ({
  SpeedInsights: jest.fn() 
}))

But the issue isn't a Next problem, it's that Analytics, etc. are ES6 Packages that JEST can't parse properly. You can find various answers around for ES6 + Jest solutions

I will give this a try, thanks for the info!