next.js: Cannot create a simple jest test
Verify canary release
- I verified that the issue exists in the latest Next.js canary release
Provide environment information
Operating System:
Platform: linux
Arch: x64
Version: #22 SMP Tue Jan 10 18:39:00 UTC 2023
Binaries:
Node: 16.17.0
npm: 8.15.0
Yarn: 1.22.19
pnpm: 7.1.0
Relevant packages:
next: 13.3.1
eslint-config-next: N/A
react: 18.2.0
react-dom: 18.2.0
Which area(s) of Next.js are affected? (leave empty if unsure)
No response
Link to the code that reproduces this issue
https://codesandbox.io/p/sandbox/lively-leftpad-ket1gt
To Reproduce
Run tests with npx jest
Describe the Bug
When I use jest with nextJest
the tests fail
Expected Behavior
Tests should pass
Which browser are you using? (if relevant)
No response
How are you deploying your application? (if relevant)
No response
About this issue
- Original URL
- State: open
- Created a year ago
- Reactions: 1
- Comments: 21 (12 by maintainers)
I already tried mock instead of using spyOn. Also, the folder structure is from the nextjs template in codesandbox so I don’t think there’s anything wrong with the folder structure here.
Sure, it is throwing up the error
Cannot redefine property: bar
in thebarMock
declaration but why does it only happen if my config is like this:But the tests pass without errors if my config is like this:
You can try it yourself. The test is simple. If you can check whether
bar
is being called at least once insidefoo
using jest regardless of what you use (spy/mock) and without using DI, I’ll close this issue. Feel free to use a “standard” folder structure if that helps.After further reading, it seems like swc won’t be fixing this
https://github.com/swc-project/swc/issues/5059
https://github.com/swc-project/swc/issues/5205
For anyone who will stumble upon this, your tests are fine. Next.js is using SWC as their compiler, which treats ts-jest transpiled tests wrong.
You can fix this by doing one of the following:
nextJest
. Just export your jest config normallynextJest
, use jest_workaround swc plugin. Add it in your next.config.jsI see. I will try it when I get back. This is how I imported it before 🤔
@kapitanluffy as mentioned in a previous comment, I’ve forked your codesandbox and included this fix which will make the test actually run.
euhm… not to just to any conclusions but it more likely seems like your test is just incorrect rather than this being an issue on Next.js 's part.