-
Notifications
You must be signed in to change notification settings - Fork 26k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(next/jest): jest can not load server-only code (#52393)
### 🧐 What's in there? At the moment, it is not possible to test code with `import 'server-only'` in app directory. When trying to load such file in jest (even with `testEnvironment: node`), the error will be: ``` ● Test suite failed to run·· x NEXT_RSC_ERR_CLIENT_IMPORT: server-only ,-[lib/util.js:1:1] 1 | /** @jest-environment node */· 2 | import 'server-only' : ^^^^^^^^^^^^^^^^^^^^ 3 | export const PI = 3.14; `----· at Object.transformSync (node_modules/next/src/build/swc/index.ts:443:25) at transformSync (node_modules/next/src/build/swc/index.ts:629:19) at Object.process (node_modules/next/src/build/swc/jest-transformer.ts:117:25) at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:619:31) at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:765:40) at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:822:19)· ``` In a nutshell: - next/swc is looking for ‘server-only’ [text in the source](https://github.com/vercel/next.js/blob/canary/packages/next-swc/crates/core/src/react_server_components.rs#L576), and throw if not configured for server - next's jest-transformer will only configure next/swc for server [if the environment is node](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/swc/jest-transformer.ts#L88) - when testing Next.js apps, your jest testEnvironment is most likely jsdom. But you can configure it [per file with docBlock](https://jestjs.io/docs/configuration#testenvironment-string), which jest-transformer ignores because it only reads the top-level configuration. This PR fixes this, by 1. reading the docblock to configure next/swc accordingly and bypass its hardcoded guard 2. mocking `server-only` so [it does not throw](https://github.com/vercel/next.js/blob/canary/packages/next/src/compiled/server-only/index.js) when loaded (jest does not read `react-server` export from package.json) Users would still have to annotate their `server-only` files with `/** @jest-environment node */` in order to test them. ### 🧪 How to test? There's a full test available: `pnpm testheadless --testPathPattern jest/server-only` Here is also a minimal reproduction: <details> <summary>app/layout.tsx</summary> ```typescript export default function RootLayout({ children }: { children: React.ReactNode }) { return (<html lang="en"><body>{children}</body></html>) } ``` </details> <details> <summary>app/page.tsx</summary> ```typescript import { PI } from '@/lib/utils' export default function Home() { return <h1>{PI}</h1> } ``` </details> <details> <summary>lib/utils.ts</summary> ```typescript import 'server-only' export const PI = 3.14 ``` </details> <details> <summary>lib/utils.test.ts</summary> ```typescript import { PI } from './utils' it('works', () => expect(PI).toEqual(3.14)) ``` </details> <details> <summary>jest.config.js</summary> ```typescript const nextJest = require('next/jest') module.exports = nextJest({ dir: './' })({ testEnvironment: 'jsdom' }) ``` </details> ### ❗ Notes to reviewers [jest-docblock](https://packagephobia.com/result?p=jest-docblock) with dependencies is only 12.5 kB. Fixes #47448
- Loading branch information
Showing
12 changed files
with
126 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
// this empty files is only here to mock server-only imports |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) Meta Platforms, Inc. and affiliates. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
{"name":"jest-docblock","main":"index.js","license":"MIT"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import { createNext } from 'e2e-utils' | ||
import { NextInstance } from 'test/lib/next-modes/base' | ||
|
||
describe('next/jest', () => { | ||
let next: NextInstance | ||
|
||
beforeAll(async () => { | ||
next = await createNext({ | ||
skipStart: true, | ||
files: { | ||
'app/page.jsx': `import { PI } from '../lib/util' | ||
export default function Home() { | ||
return <h1>{PI}</h1> | ||
}`, | ||
'app/layout.jsx': `export default function RootLayout({ children }) { | ||
return ( | ||
<html lang="en"> | ||
<body>{children}</body> | ||
</html> | ||
) | ||
}`, | ||
'app/page.test.jsx': `import { render, screen } from '@testing-library/react' | ||
import '@testing-library/jest-dom' | ||
import Page from './page' | ||
it('works from client-side code', () => { | ||
render(<Page />) | ||
expect(screen.getByRole('heading')).toHaveTextContent('3.14') | ||
})`, | ||
'lib/util.js': `/** @jest-environment node */ | ||
import 'server-only' | ||
export const PI = 3.14;`, | ||
'lib/utils.test.ts': `import { PI } from './util' | ||
it('works from server-side code', () => { | ||
expect(PI).toEqual(3.14) | ||
})`, | ||
'jest.config.js': `module.exports = require('next/jest')({ dir: './' })({ testEnvironment: 'jsdom' })`, | ||
}, | ||
buildCommand: `yarn jest`, | ||
dependencies: { | ||
'@types/react': 'latest', | ||
'@testing-library/jest-dom': '5.16.5', | ||
'@testing-library/react': '13.0.0', | ||
jest: '27.4.7', | ||
}, | ||
}) | ||
}) | ||
|
||
afterAll(() => next.destroy()) | ||
|
||
it('can run test against server side components', async () => { | ||
try { | ||
await next.start() | ||
} finally { | ||
expect(next.cliOutput).toInclude('Tests: 2 passed, 2 total') | ||
} | ||
}) | ||
}) |