Issue unit testing with nextjs and absolute imports
See original GitHub issueCurrent behavior
We use a simple tsconfig
with baseUrl: "."
so all our imports are relative to the root of the project, like import Button from "components/Button"
. No issues with integration tests. However, when running a unit test and importing a simple function from a file that has other relative imports (like import {anotherUtil} from 'utils/someOtherUtils'
, Cypress does not understand this relative import.
The error message looks like:
Error: Webpack Compilation Error
./utils/someMath.ts
Module not found: Error: Can't resolve 'utils/addTwoNumbers' in '/Users/bradycaspar/code/test/cypress-next/utils'
resolve 'utils/addTwoNumbers' in '/Users/bradycaspar/code/test/cypress-next/utils'
Parsed request is a module
using description file: /Users/bradycaspar/code/test/cypress-next/package.json (relative path: ./utils)
Field 'browser' doesn't contain a valid alias configuration
Looked for and couldn't find the file at the following paths:
[/Users/bradycaspar/code/test/cypress-next/utils/node_modules]
[/Users/bradycaspar/code/test/node_modules]
[/Users/bradycaspar/code/node_modules]
[/Users/node_modules]...
The error message makes it sound like it is searching for this import in node_modules
and nowhere else.
This works if the import is removed from the file or the import format changes to import Button from './Button'
. However if possible I’d prefer to not change the imports across the whole app 😄
Desired behavior
The imports with the format we use are found as expected.
Test code to reproduce
I created a minimal repro here: https://github.com/bscaspar/cypress-next-import-error-example.
Cypress Version
^9.5.1
Other
Am I missing a simple config? Any help is appreciated!
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (2 by maintainers)
Top GitHub Comments
Looking forward for this next release with better support for Next 12!
Yes, I did found a workaround - I ended up writing a custom transformer for browserify. Regarding why I’m using it, I have no particular reason - I was following the official docs on how to have coverage reports for both my unit & integration tests.
Sorry, I’ve not been tracking this issue. We are in the process of updating our Next.js plugin to work with v11 and v12 with more thorough code around the various edge cases. This should be released w/ Cypress 10 (next few weeks).
In the meantime: it seems you found a workaround? Also, any particular reason to use the browserify plugin when Next.js is using webpack?